Multiply multiple columns by fixed values in Pandas

Viewed 653

I have a pandas df that looks something like below.

how would i be able to multiple columns v2, v3, and v4 by a fixed value? (I am trying to multiple these columns by .23, .43, and .56 respectifully.

v1. v2. v3.     v4
1   1   17.70%  18.00%
2   2   16.60%  13.00%
3   3   10.60%  25.00%
4   4   29.10%  18.00%
5   5   20.50%  20.50%
6   6   1.10%   1.10%
7   7   1.10%   1.10%
8   8   1.10%   1.10%
9   9   2.40%   2.20%

I thought i would be able to do something like this

df = df[(df['v2'] * .23), (df['v3'] * .43), , (df['v4'] * .56)]
2 Answers

Suppose you have this dataframe:

   v1  v2      v3      v4
0   1   1  17.70%  18.00%
1   2   2  16.60%  13.00%
2   3   3  10.60%  25.00%
3   4   4  29.10%  18.00%
4   5   5  20.50%  20.50%
5   6   6   1.10%   1.10%
6   7   7   1.10%   1.10%
7   8   8   1.10%   1.10%
8   9   9   2.40%   2.20%

First step is "clean" your data - remove % and convert it to floats:

df["v3"] = pd.to_numeric(df["v3"].str.strip("%"))
df["v4"] = pd.to_numeric(df["v4"].str.strip("%"))

Then you can multiply your columns:

df["v2"] = df["v2"] * 0.23
df["v3"] = df["v3"] * 0.43
df["v4"] = df["v4"] * 0.56

print(df)

The result:

   v1    v2      v3      v4
0   1  0.23   7.611  10.080
1   2  0.46   7.138   7.280
2   3  0.69   4.558  14.000
3   4  0.92  12.513  10.080
4   5  1.15   8.815  11.480
5   6  1.38   0.473   0.616
6   7  1.61   0.473   0.616
7   8  1.84   0.473   0.616
8   9  2.07   1.032   1.232

To convert it back to %-form:

df["v3"] = df["v3"].apply("{:.2f}%".format)
df["v4"] = df["v4"].apply("{:.2f}%".format)
print(df)

Prints:

   v1    v2      v3      v4
0   1  0.23   7.61%  10.08%
1   2  0.46   7.14%   7.28%
2   3  0.69   4.56%  14.00%
3   4  0.92  12.51%  10.08%
4   5  1.15   8.81%  11.48%
5   6  1.38   0.47%   0.62%
6   7  1.61   0.47%   0.62%
7   8  1.84   0.47%   0.62%
8   9  2.07   1.03%   1.23%

So here's your DataFrame:

import pandas as pd 

df = pd.DataFrame(
    [
        (1, 1, '17.70%', '18.00%'),
        (2, 2, '16.60%', '13.00%'),
        (3, 3, '10.60%', '25.00%'),
        (4, 4, '29.10%', '18.00%'),
        (5, 5, '20.50%', '20.50%'),
        (6, 6, '1.10%', '1.10%'),
        (7, 7, '1.10%', '1.10%'),
        (8, 8, '1.10%', '1.10%'),
        (9, 9, '2.40%', '1.40%'),
    ], 
    columns=['v1', 'v2', 'v3', 'v4']
)

You now need a map() to apply a function over columns v3 and v4:

df['v2'] = df['v2'] * 0.23
df['v3'] = df['v3'].map(lambda c: f"{float(c.strip('%')) * 0.43:.2f}%")
df['v4'] = df['v4'].map(lambda c: f"{float(c.strip('%')) * 0.56:.2f}%")

And the output should be:

print(df)
   v1    v2      v3      v4
0   1  0.23   7.61%  10.08%
1   2  0.46   7.14%   7.28%
2   3  0.69   4.56%  14.00%
3   4  0.92  12.51%  10.08%
4   5  1.15   8.81%  11.48%
5   6  1.38   0.47%   0.62%
6   7  1.61   0.47%   0.62%
7   8  1.84   0.47%   0.62%
8   9  2.07   1.03%   0.78%
Related