'multiply column values by a different constant per row

vars   x        y         z
a     0.00045   0.00065   0.0076
b     1.0       1.0       1.0
c     0.0000067 0.0000043  0.00067

I need to multiply certain variables with a particular constant, for example a*100 and b*1000, but keep c as constant, so that it will be easier to compare the variables. How to do it?



Solution 1:[1]

You can multiply by a dictionary after setting "vars" as the index:

df.set_index('vars').mul({'a': 100, 'b': 1000, 'c': 1}, axis=0)

output:

                x            y           z
vars                                      
a        0.045000     0.065000     0.76000
b     1000.000000  1000.000000  1000.00000
c        0.000007     0.000004     0.00067

If you have many columns an only want to multiply a few you can use a Series and combine_first:

df = df.set_index('vars') 
    
df.mul(pd.Series({'a': 100, 'b': 1000}), axis=0).combine_first(df)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1