Home > OS >  Is there a way to achieve this with groupby/pivot table in pandas?
Is there a way to achieve this with groupby/pivot table in pandas?

Time:10-19

How to transform this dataframe

Year    Gender  Count
2018    Female  4010
2018    Male    19430
2019    Female  3212
2019    Male    16138

To

Year    Male    Female    Ratio  

2018   19430    4010        0.21

2019   16138    3212        0.20

using groupby/pivot/any custom function????

CodePudding user response:

Something like this:

new_df = df.pivot("Year", "Gender", "Count").assign(Ratio=lambda r: r.Female / r.Male)

# To remove the "Gender" name from column index
new_df.columns.name = None 

# Reset row index as column
new_df = new_df.reset_index()

Result:

   Year  Female   Male     Ratio
0  2018    4010  19430  0.206382
1  2019    3212  16138  0.199033
  • Related