27

If I have the following 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!").

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?

Thanks

Garrett
  • 47,045
  • 6
  • 61
  • 50
beardc
  • 20,283
  • 17
  • 76
  • 94

1 Answers1

23

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
Garrett
  • 47,045
  • 6
  • 61
  • 50
  • 2
    While the accepted answer seems to solve the problem for the OP, it does not actually address the question posed in the title. I.e. convert a groupby into a multi-index directly. It goes back to the original dataframe, not the grouped object. – JohnT May 01 '23 at 12:48