I am trying to do a row value divide by their column sum. I think I could do it row by row and then concat them together but I am wondering if there's a more efficient way to do it in pandas.
abc = {
'fruits': {0: 'apple', 1: 'orange', 2: 'total'},
'Monday': {0: 2, 1: 4, 2: 6},
'Tuesday': {0: -2, 1: -6, 2: -8},
'Wednesday': {0: -40, 1: -65, 2: -105}
}
pd.DataFrame.from_dict(abc)
fruits Monday Tuesday Wednesday
0 apple 2 -2 -40
1 orange 4 -6 -65
2 total 6 -8 -105
Expected output:
fruits Monday Tuesday Wednesday
0 apple 0.33 0.25 0.38
1 orange 0.67 0.75 0.62
CodePudding user response:
df = pd.DataFrame.from_dict(abc)
df.iloc[:,1:] = df.iloc[:,1:] / df.iloc[-1,1:]
df = df[:-1]
df
df.iloc[:,1:]
takes all columns except fruits. df.iloc[-1,1:]
is the last row of the dataframe, which is total. df = df[:-1]
assigns all rows except the total row as a df