【问题标题】:Convert pandas group by object to multi-indexed Dataframe按对象将熊猫分组转换为多索引数据框
【发布时间】:2012-12-27 10:29:24
【问题描述】:

如果我有以下数据框

>>> df = pd.DataFrame({'Name': ['Bob'] * 3 + ['Alice'] * 3, \
'Destination': ['Athens', 'Rome'] * 3, 'Length': np.random.randint(1, 6, 6)}) 
>>> df    
  Destination  Length   Name
0      Athens       3    Bob
1        Rome       5    Bob
2      Athens       2    Bob
3        Rome       1  Alice
4      Athens       3  Alice
5        Rome       5  Alice

我可以按名称和目的地进行搜索...

>>> grouped = df.groupby(['Name', 'Destination'])
>>> for nm, gp in grouped:
>>>     print nm
>>>     print gp
('Alice', 'Athens')
  Destination  Length   Name
4      Athens       3  Alice
('Alice', 'Rome')
  Destination  Length   Name
3        Rome       1  Alice
5        Rome       5  Alice
('Bob', 'Athens')
  Destination  Length Name
0      Athens       3  Bob
2      Athens       2  Bob
('Bob', 'Rome')
  Destination  Length Name
1        Rome       5  Bob

但我想要一个新的多索引数据框,看起来像

                Length
Alice   Athens       3
        Rome         1
        Rome         5
Bob     Athens       3
        Athens       2
        Rome         5

似乎应该有一种方法来执行类似Dataframe(grouped) 的方法来获取我的多索引数据帧,但我得到了一个PandasError(“DataFrame 构造函数未正确调用!”)。

最简单的方法是什么?另外,任何人都知道是否可以选择将 groupby 对象传递给构造函数,或者我只是做错了吗?

谢谢

【问题讨论】:

    标签: python group-by dataframe pandas multi-index


    【解决方案1】:

    由于您没有聚合索引相似的行,请尝试使用列名列表设置索引。

    In [2]: df.set_index(['Name', 'Destination'])
    Out[2]: 
                       Length
    Name  Destination        
    Bob   Athens            3
          Rome              5
          Athens            2
    Alice Rome              1
          Athens            3
          Rome              5
    

    【讨论】:

      猜你喜欢
      • 2016-01-20
      • 2019-09-28
      • 2020-02-13
      • 2019-12-07
      • 2021-12-01
      • 1970-01-01
      • 2015-11-10
      • 2018-02-07
      相关资源
      最近更新 更多