Issue
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'
Solution
use df.columns = df.columns.get_level_values(1)
after that you can use ratio = df.Captive / df.Wild
Answered By - user96564
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.