Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.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
Pandas 通过单个列搜索具有分层索引的数据帧_Pandas_Search_Indexing_Hierarchical - Fatal编程技术网

Pandas 通过单个列搜索具有分层索引的数据帧

Pandas 通过单个列搜索具有分层索引的数据帧,pandas,search,indexing,hierarchical,Pandas,Search,Indexing,Hierarchical,我正在使用此数据帧: import pandas as pd df = pd.DataFrame([['A', 'one', 105], ['A', 'two', 101], ['A', 'three', 103], ['B','one', 101], ['B','two', 1102], ['B','three', 1050]], columns=['c1', 'c2', 'c3']) df = df

我正在使用此数据帧:

import pandas as pd
df = pd.DataFrame([['A', 'one',  105], ['A', 'two',  101], ['A', 'three',  103],
                      ['B','one',  101], ['B','two',  1102], ['B','three',  1050]],
                   columns=['c1', 'c2', 'c3'])
df = df.set_index(['c1', 'c2'])
df
返回

               c3
c1    c2    
A     one     105
      two     101
      three   103
B     one     101
      two     1102
      three   1050
。。。我想按c3列排序,保留行和c1排序,得到以下结果:

              c3
c1    c2    
A     one     105
      three   103
      two     101
B     two     1102
      three   1050
      one     101
我还没能想出一个不把c1排序搞混的方法。特别是,最终的df.sort_索引返回KeyError:“c1”

IIUC您可以执行以下操作:

out = (df.sort_values(['c3','c1'],ascending=False)
      .reindex(df.index.get_level_values(0).unique(),level=0))
IIUC你可以做:

out = (df.sort_values(['c3','c1'],ascending=False)
      .reindex(df.index.get_level_values(0).unique(),level=0))

我想你可以用:

df.sort_values(['c1','c3'], ascending=False).groupby(['c1','c3']).agg(lambda x: x)
输出:

            c3
c1 c2         
B  two    1102
   three  1050
   one     101
A  one     105
   three   103
   two     101

我想你可以用:

df.sort_values(['c1','c3'], ascending=False).groupby(['c1','c3']).agg(lambda x: x)
输出:

            c3
c1 c2         
B  two    1102
   three  1050
   one     101
A  one     105
   three   103
   two     101

我还是不明白你的逻辑。您是否尝试按c1升序和c3降序排序?我看不到c2和c3中的逻辑或排序。如果你按c2排序,那么它应该是1-3-2,如果按c3排序,那么1102应该在顶部或底部。1102应该在顶部,因为它大于1050,同意@TYZI仍然没有得到你的逻辑。您是否尝试按c1升序和c3降序排序?我看不到c2和c3中的逻辑或排序。如果你按c2排序,那么它应该是1-3-2,如果按c3排序,那么1102应该在顶部或底部。1102应该在顶部,因为它大于1050。同意@TYZYes,你看穿了我的打字错误,谢谢@anky_91是groupby更好的选择还是reindex?是的,你看穿了我的打字错误,就这样,谢谢@anky_91是groupby更好的选择还是重新索引?谢谢@anky_91,我不确定,这就是为什么我asked@anky_91当然,我会让你知道的谢谢@anky_91,我不确定,这就是为什么我asked@anky_91当然,我会让你知道的