Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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_Group By_Dataframe_Pandas_Multi Index - Fatal编程技术网

Python 将按对象分组转换为多索引数据帧

Python 将按对象分组转换为多索引数据帧,python,group-by,dataframe,pandas,multi-index,Python,Group By,Dataframe,Pandas,Multi Index,如果我有以下数据帧 >>> 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 Rom

如果我有以下数据帧

>>> 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
(“未正确调用数据帧构造函数!”)

最简单的方法是什么?还有,有人知道是否有将groupby对象传递给构造函数的选项,或者我只是做错了吗


谢谢

因为您没有聚合类似索引的行,请尝试使用列名列表设置索引

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