EGM8686
EGM8686

Reputation: 1572

Multiply multiple columns conditionally by one column (easy in Excel)

I have a dataframe like this:

a   b   c   d   m1   m2 
3   2   2   2   5    4 
1   4   1   1   5    4   
3   2   2   3   5    4

I would like to multiply a and b for m1 and c and d for m2:

a   b   c   d   m1   m2 
15  10  8   8   5    4 
5   20  4   4   5    4   
15  10  8   12  5    4

Also retaining the original dataframe structure, This is fairly simple in Excel, but Pandas is proving complicated since if I try the first multiplication (m1) then the DF drops non used columns.

Cheers!

Upvotes: 0

Views: 198

Answers (2)

jpp
jpp

Reputation: 164693

Here's one way using np.repeat:

df.iloc[:, :4] *= np.repeat(df.iloc[:, 4:].values, 2, axis=1)

print(df)

    a   b  c   d  m1  m2
0  15  10  8   8   5   4
1   5  20  4   4   5   4
2  15  10  8  12   5   4

Upvotes: 1

jezrael
jezrael

Reputation: 862751

Use mul with subset of columns defined by list of columns names:

df[['a', 'b']] = df[['a', 'b']].mul(df['m1'], axis=0)
df[['c', 'd']] = df[['c', 'd']].mul(df['m2'], axis=0)

print (df)
    a   b  c   d  m1  m2
0  15  10  8   8   5   4
1   5  20  4   4   5   4
2  15  10  8  12   5   4

Upvotes: 1

Related Questions