Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally multiply values in DataFrame row

here is an example DataFrame:

df = pd.DataFrame([[1,0.5,-0.3],[0,-4,7],[1,0.12,-.06]], columns=['condition','value1','value2'])

I would like to apply a function which multiples the values ('value1' and 'value2' in each row by 100, if the value in the 'condition' column of that row is equal to 1, otherwise, it is left as is.

presumably some usage of .apply with a lambda function would work here but I am not able to get the syntax right. e.g.

df.apply(lambda x: 100*x if x['condition'] == 1, axis=1) 

will not work

the desired output after applying this operation would be:

enter image description here

like image 707
laszlopanaflex Avatar asked Sep 02 '25 15:09

laszlopanaflex


1 Answers

As simple as

df.loc[df.condition==1,'value1':]*=100
like image 143
BENY Avatar answered Sep 05 '25 09:09

BENY