Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute row percentages in pandas DataFrame?

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?

like image 617
yourselvs Avatar asked Jun 12 '18 15:06

yourselvs


2 Answers

div + sum

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
like image 108
jpp Avatar answered Oct 29 '22 16:10

jpp


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
like image 29
sacuL Avatar answered Oct 29 '22 16:10

sacuL