Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiply observations in one column by every other columns in Python

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'])

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading