0

I have the following code:

import pandas as pd
arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
          ['Captive', 'Wild', 'Captive', 'Wild']]
index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},
                  index=index)
df = df.unstack(1)

As a result, I've got a dataframe:

       Max Speed       
Type     Captive   Wild
Animal
Falcon     390.0  350.0
Parrot      30.0   20.0

How can I convert column index to the normal column for further calculations?

E.g. when I tried to calculate the ratio:

ratio = df.Captive / df.Wild

I am getting an error:

'DataFrame' object has no attribute 'Captive'

Andrey
  • 5,932
  • 3
  • 17
  • 35
  • 1
    What do you mean "convert column index to the normal column"? You can use the MultiIndex `df[('Max Speed', 'Captive')] / df[('Max Speed', 'Wild')]` or droplevel `df = df.unstack(1).droplevel(level=0, axis=1)` if you want to get rid of `Max Speed`. – Henry Ecker Nov 06 '21 at 19:43
  • @HenryEcker as far as I uderstand - the second suggestion should be `df = df.droplevel(level=0, axis=1)` – Andrey Nov 06 '21 at 20:09
  • I was adding it to the end of your already present code (`df = df.unstack(1)`). @Andrey The multi level comes from unstacking so the removal should be in the same chain. – Henry Ecker Nov 06 '21 at 20:21
  • I've closed this as a duplicate since the accepted answer matches [BENY's answer from 2018](https://stackoverflow.com/a/53449204/15497888) "`df.columns=df.columns.get_level_values(1)`" – Henry Ecker Nov 06 '21 at 20:26

2 Answers2

4

use df.columns = df.columns.get_level_values(1)

after that you can use ratio = df.Captive / df.Wild

user96564
  • 1,578
  • 5
  • 24
  • 42
1

df is now a dataframe that contains another dataframe.

This'll work:

ratio = df['Max Speed'].Captive / df['Max Speed'].Wild