Home > Software engineering >  Multiply observations in one column by every other columns in Python
Multiply observations in one column by every other columns in Python

Time:03-02

If I have many columns, how would I multiply the observations in every column by their corresponding probabilities (stored in the probability column)?

If I wanted to do just one column, I could do

df['new'] = df['0'] * df['probability'] 

but I want to do this with many columns and keep the resulting answers (whether replace old observations with these or store answers in new data frame).

My thought was to use apply...like

df_t.assign(new_df = lambda df: df.apply(max * df.x, axis=1, raw=False, result_type=None))

but this doesn't quite get me there (or work), and I'm not sure how to get there. Df.x would stand in for any column.

df = pd.DataFrame([[1.5, 2.3, .4], [5.6, 2.4,  .2], [5,  4,  .2]], columns=['0', '1', 'probability'])

CodePudding user response:

We could multiply with mul on axis:

cols = df.columns.drop('probability')
df[cols] = df[cols].mul(df['probability'], axis=0)

Output:

      0     1  probability
0  0.60  0.92          0.4
1  1.12  0.48          0.2
2  1.00  0.80          0.2
  • Related