简体   繁体   English

将pandas group by object转换为多索引Dataframe

[英]Convert pandas group by object to multi-indexed Dataframe

If I have the following Dataframe 如果我有以下Dataframe

>>> 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

I can goup by name and destination... 我可以通过名字和目的地来集合......

>>> 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

but I would like a new multi-indexed dataframe out of it that looks something like 但我希望一个新的多索引数据框看起来像

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

It seems there should be a way to do something like Dataframe(grouped) to get my multi-indexed Dataframe, but instead I get a PandasError ("DataFrame constructor not properly called!"). 似乎应该有一种方法可以做一些像Dataframe(grouped)这样的东西来获取我的多索引Dataframe,但是我得到一个PandasError (“DataFrame构造函数没有被正确调用!”)。

What is the easiest way to get this? 最简单的方法是什么? Also, anyone know if there will ever be an option to pass a groupby object to the constructor, or if I'm just doing it wrong? 此外,任何人都知道是否会有一个选项将groupby对象传递给构造函数,或者我是否只是做错了?

Thanks 谢谢

Since you're not aggregating similarly indexed rows, try setting the index with a list of column names. 由于您没有聚合类似的索引行,因此请尝试使用列名列表设置索引。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM