sequence_hard
sequence_hard

Reputation: 5385

How to get column value as percentage of other column value in pandas dataframe

I have a question. I have a relatively huge pandas dataframe like this one:

df:

   Column1  Column2  Column3  Column4
0     100      50       25       10
1     200      100      50       10
2     10       10       5        5
3     20       15       10       5
4     10       7        7        7

What I now would like to do with it is adding strings to each value as follows: For each value in Column2, add a string displaying this value as percentage of the value in Column1. Then, for all values in Columns3 until the end (ColumnN) add to each value a string displaying this value as percentage of Column2. The final result would look like this:

df:

       Column1  Column2      Column3       Column4
    0     100      50 (50%)     25 (50%)      10 (20%)
    1     200      100(50%)     50 (50%)      10 (10%)
    2     10       10 (100%)    5  (50%)       5 (50%)
    3     20       15 (75%)     10 (66,6%)     5 (33,3%)
    4     10       7  (70%)     7  (100%)      7 (100%)

My idea of finally adding the strings to the corresponding values would maybe be something like df['col'] = 'str' + df['col'].astype(str), but I don't really know how to start with it, as for example getting the percentage values for each value for example. An help on this would be really appreciated.

Upvotes: 1

Views: 720

Answers (1)

Zero
Zero

Reputation: 76917

Something like this?

In [95]:  (df.astype(str) + 
           ' (' + 
           df.apply(lambda x: (100 * x / x['Column1']), axis=1).astype(str) +
           '%)')
Out[95]:
        Column1      Column2     Column3     Column4
0  100 (100.0%)   50 (50.0%)  25 (25.0%)  10 (10.0%)
1  200 (100.0%)  100 (50.0%)  50 (25.0%)   10 (5.0%)
2   10 (100.0%)  10 (100.0%)   5 (50.0%)   5 (50.0%)
3   20 (100.0%)   15 (75.0%)  10 (50.0%)   5 (25.0%)
4   10 (100.0%)    7 (70.0%)   7 (70.0%)   7 (70.0%)

Upvotes: 3

Related Questions