Pandas多索引错误:多索引切片需要对索引进行排序

2024-04-26 03:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我为什么我得到这个多索引未排序错误吗

mindex = pd.MultiIndex.from_product(
                                        [[2013,2014],[1,2]],
                                        names = ['Year', 'Visit']
                                    )
mcolumn = pd.MultiIndex.from_product(
                                        [['Sue','Bob','John'],['Heart Rate', 'Temperature']],
                                        names = ['Name','Parameter']
                                    )

data = np.random.randint(44, 92, size=(4,6))
df = pd.DataFrame( data, columns = mcolumn, index = mindex)
idx = pd.IndexSlice

df.loc[ idx[2013, 2], idx['Bob':'Guido', 'Heart Rate']  ]

Error: 'MultiIndex slicing requires the index to be lexsorted: slicing on levels [0], lexsort depth 0'

大约一个月前,当我在同一个Jupyter笔记本上执行相同的代码时,我没有遇到这个错误。但现在我要面对它。有什么建议吗


Tags: fromdfdataindexratenames错误product