Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 排序多索引_Python_Pandas - Fatal编程技术网

Python 排序多索引

Python 排序多索引,python,pandas,Python,Pandas,我已使用另一个数据帧创建了具有多索引的数据帧: arrays = [df['bus_uid'], df['bus_type'], df['type'], df['obj_uid'], df['datetime']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['bus_uid', 'bus_type', 'type',

我已使用另一个数据帧创建了具有多索引的数据帧:

arrays = [df['bus_uid'], df['bus_type'], df['type'],
          df['obj_uid'], df['datetime']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['bus_uid', 'bus_type', 'type',
                                                 'obj_uid', 'datetime'])
multindex_df = pd.DataFrame(df['val'].values, index=index)
正如文档中所描述的那样,这工作得很好

在文档中还指出,需要对标签进行分类,以便在“需要使用多索引进行分类”下正确使用索引和切片功能

但不知怎么的

multindexed_df.sort_index(level=0)

不再工作并抛出TypeError:sort_index()获得意外的关键字参数“level”

在sort_index()上查找对象信息时,它看起来是“by”是我的新朋友,而不是“levels”:


我的问题是:如何对多重索引进行排序,以便所有功能(切片等)都能正常工作?

答案取决于您使用的熊猫版本。使用最新的pandas(>=0.17.0),您确实可以使用
level
关键字指定对多索引的哪个级别进行排序:

df = df.sort_index(level=0)
但是,如果您有一只年龄较大的熊猫(<0.17.0),则此
级别
关键字尚不可用,但您可以使用
sortlevel
方法:

df = df.sortlevel(level=0)
但请注意,如果要对所有级别进行排序,则无需指定
级别
关键字,只需执行以下操作:

df = df.sort_index()
这将适用于熊猫的最新版本和旧版本



有关排序API中这些更改的摘要,请参见我的错误!我正在开发版本0.16.2,现在更新到0.17.1。那么仅仅应用multindex_df.sort_索引(inplace=True)就足以获得所有功能了?谢谢从有序索引切片现在会弹出一个错误:1。“idx=pd.indexlice”2。“subset=multindex_df.loc[idx['el:DE22C'],['el'],['input'],:,:,:]”带来了“keyrerror:“多索引切片要求索引是完全lexsorted的tuple len(5),lexsort depth(0)”,这又是我的错误。我在重新创建之后忘记了对索引进行排序;)非常感谢!
df = df.sortlevel(level=0)
df = df.sort_index()