I have this dataframe:
df = pd.DataFrame([["A", "2000-01", "100", "10%"],
["A", "2000-02", "200", "20%"],
["B", "2000-01", "150", "15%"],
["B", "2000-02", "150", "15%"],
["C", "2000-01", "250", "25%"],
["C", "2000-02", "350", "35%"],
["D", "2000-01", "500", "50%"],
["D", "2000-02", "300", "30%"],],
columns=["Label", "Date", "Count", "Percentage"])
I want to transpose it as
Date | A | B | C | D |
---|---|---|---|---|
2000-01 | 10% | 15% | 25% | 50% |
2000-02 | 20% | 15% | 35% | 30% |
with
df_T= df.groupby(['Date','Label']).sum().transpose().stack(0).reset_index()
del df_T['level_0']
df_T[['A','B','C','D']] = df_T[['A','B','C','D']].apply(lambda x: x/x.sum(), axis=1)
I kinda got it.
But I'm failing with the percentages format. Thought this would work, but didn't (got an error):
df_T['A','B','C','D'] = df_T['A','B','C','D'].map('{:,.2f}%'.format)
What am I missing here?
Very important also, I would like to print some output as:
"In 2000-01, A = 10%, B = 15%, C = 25%, D = 50%. \n In 2000-02, A = 20%, B = 15%, C = 35%, D = 30%. "
to have a description text for a subsequent plot as an image (in case the image is not visible on the page and accessibility matters).
How's the best way to do it?
I'd appreciate some help!