Home > OS >  Calculate every row in a pandas dataframe with a value specific to that row
Calculate every row in a pandas dataframe with a value specific to that row

Time:04-07

I have a fairly big dataframe with around 20 columns containing floats, and one column with a factor.

index col1 col2 factor
row1 5.2 10.5 1.01
row2 92.61 141.7 1.3
row3 2.75 205.56 1.9

I want to multiply every value in each row with the factor for that row.

How can I do this fairly fast?

I have considered df.iterrows() to loop and try to multiply all values with row['Factor'], but this has not been successful.

Any suggestion is appreciated.

CodePudding user response:

For in place modification, you could use filter to select the columns, mul to perform the multiplication, and update to update the DataFrame with the new values:

df.update(df.filter(like='col').mul(df['factor'], axis=0))

NB. with update, the modification is in place, there is no output, df is modified directly.

resulting df:

  index     col1     col2  factor
0  row1    5.252   10.605    1.01
1  row2  120.393  184.210    1.30
2  row3    5.225  390.564    1.90

CodePudding user response:

Use Index.difference for columns names for multiple by column with DataFrame.mul:

cols = df.columns.difference(['factor'])
df[cols] = df[cols].mul(df['factor'], axis=0)
print (df)
         col1     col2  factor
row1    5.252   10.605    1.01
row2  120.393  184.210    1.30
row3    5.225  390.564    1.90
  • Related