Home > Software engineering >  Need to multiply each column by the top cell in that column in pandas
Need to multiply each column by the top cell in that column in pandas

Time:11-12

I have the following DF:

Score1 Score2 Score3
1      3      4
0      0      0
2      3      5
1      6      2

And I want to multiply each column by the top of that columns cell. So the output would be :

Score1 Score2 Score3
1      3      4
0      0      0
2      9     20
1     18      8

How can I go about doing this?

CodePudding user response:

Use df.update

df.update(df.iloc[0] * df.iloc[1:])
print(df)

# Output:
   Score1  Score2  Score3
0     1.0     3.0     4.0
1     0.0     0.0     0.0
2     2.0     9.0    20.0
3     1.0    18.0     8.0

Or combine_first:

df = df.iloc[0].mul(df.iloc[1:]).combine_first(df)
print(df)

# Output:
   Score1  Score2  Score3
0       1       3       4
1       0       0       0
2       2       9      20
3       1      18       8

CodePudding user response:

We can also prevent loss of dtypes/values by using iloc on both sides of assignment. This removes the need to merge back to fill created NaN values:

df.iloc[1:, :] = df.iloc[1:, :] * df.iloc[0, :]

Or with assignment by multiplication:

df.iloc[1:, :] *= df.iloc[0, :]

Or with explicit axis alignment via DataFrame.mul:

df.iloc[1:, :] = df.iloc[1:, :].mul(df.iloc[0, :], axis=1)

All options produce df:

   Score1  Score2  Score3
0       1       3       4
1       0       0       0
2       2       9      20
3       1      18       8

Setup:

import pandas as pd

df = pd.DataFrame({
    'Score1': [1, 0, 2, 1], 'Score2': [3, 0, 3, 6], 'Score3': [4, 0, 5, 2]
})
  • Related