Convert Group-By Result to_frame and reset level
Lets take a data frame with multiple columns and rows just like the above table
Now let’s try to get what are vehicles owned by each person in a new data frame. So for that we need basically convert this data frame to a new dataframe. One column will have name and another column will have the vehicle in an array format.
import pandas as pd data_dic = {'Name':['Subhasis', 'Subhasis', 'Keerthan'], 'Vehicle':['Kia','Gixer','Suzuki'] } data_dic df = pd.DataFrame(data_dic) df
The above code will create initial dataframe
df.groupby('Name')['Vehicle'].apply(list).to_frame()
The above code will group the vehicles per Name. But if you notice the columns are on a different level.
df.groupby('Name')['Vehicle'].apply(list).to_frame().reset_index()
To get it into a single level you can use reset_index() as above code. This by below parameter takes ( level=None, drop=False, inplace=False, col_level=0, col_fill=”)
Originally published at http://theleadcoder.wordpress.com on May 20, 2021.