I have my data in a pandas DataFrame, and it looks like the following:
cat val1 val2 val3 val4
A 7 10 0 19
B 10 2 1 14
C 5 15 6 16
I'd like to compute the percentage of the category (cat
) that each value has.
For example, for category A
, val1
is 7 and the row total is 36. The resulting value would be 7/36, so val1
is 19.4% of category A
.
My expected result would look like the folowing:
cat val1 val2 val3 val4
A .194 .278 .0 .528
B .370 .074 .037 .519
C .119 .357 .143 .381
Is there an easy way to compute this?
For a vectorised solution, divide the dataframe along axis=0
by its sum over axis=1
. You can use set_index
+ reset_index
to ignore the identifier column.
df = df.set_index('cat')
res = df.div(df.sum(axis=1), axis=0)
print(res.reset_index())
cat val1 val2 val3 val4
0 A 0.194444 0.277778 0.000000 0.527778
1 B 0.370370 0.074074 0.037037 0.518519
2 C 0.119048 0.357143 0.142857 0.380952
You can do this using apply
:
df[['val1', 'val2', 'val3', 'val4']] = df[['val1', 'val2', 'val3', 'val4']].apply(lambda x: x/x.sum(), axis=1)
>>> df
cat val1 val2 val3 val4
0 A 0.194444 0.277778 0.000000 0.527778
1 B 0.370370 0.074074 0.037037 0.518519
2 C 0.119048 0.357143 0.142857 0.380952
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With