ReinholdN
ReinholdN

Reputation: 562

Divide a values among several columns based on its percentage

df = pd.DataFrame({ 'colors': ['red', 'white', 'blue'],
'numbers': [1, 2, 3],
'numbers1': [2, 1, 0],
'numbers3': [4, 3, 0],
'Total': [7, 6,3]})



    colors  n   n1  n3  Total
0   red     1   2   4   7
1   white   2   1   3   6
2   blue    3   0   0   3

dfpct = df.iloc[::,1:-1].div(df.Total, axis=0).fillna(0)
dfpct

numbers         numbers1    numbers3
0   0.142857    0.285714    0.571429
1   0.333333    0.166667    0.500000
2   1.000000    0.000000    0.000000

The code above gives me the percentage of each row per column. Now I have a new total value that I would like to insert to each row based on each row percentage, in another words replace the percentage with an actual value.

The new Total value would be divided by its value in percentage and inserted in the row, or replace.

For instance the new total would be

Total1 = [10, 6, 8]
numbers         numbers1    numbers3
0   0.142857    0.285714    0.571429
new 14.3        2.86        5.71
and so on

Thanks

Upvotes: 0

Views: 232

Answers (1)

BENY
BENY

Reputation: 323306

Check with mul

out = dfpct.mul([10,6,8],axis=0)
Out[279]: 
    numbers  numbers1  numbers3
0  1.428571  2.857143  5.714286
1  2.000000  1.000000  3.000000
2  8.000000  0.000000  0.000000

Upvotes: 1

Related Questions