0

I am having pandas dataframe like this

A    B    D    E
2    12   1    2
3    54   1    4
10   2    1    1

I would like to multiply values in C and D column by the value in A, but keep values in B column. So from the dataframe above, the result I would get would be :

A    B    D    E
2    12   2    4
3    54   3    12
10   2    10   10

However, I have many columns I want to modify, not just 2 like in the example. Therefore I would like to know what is the most efficient way to do this.

I was looking at DataFrame.assign function but with that, it seems like I can only modify 1 column at the time.

Thanks !

4
  • Won't df[col_list] * df['A'] just work? Commented Aug 11, 2015 at 16:05
  • Inspired by DSM's solution I tried a little modification fo yours as df.loc[:,col_list] = df[col_list] * df['A'] and surprisingly it got me NaNs in all the col_list columns. I wonder why, the datatype in both col_list collumns and "A" columns are numpy.float64 Commented Aug 11, 2015 at 18:15
  • Hmm, I think there is some issue with the broadcasting here, try this: df[col_list] = df[col_list].mul(df['A'], axis=0) Commented Aug 11, 2015 at 18:18
  • Basically it looks like the broadcasting is happening along the wrong axes resulting in some funny df filled with NaN values returned, if you did this then it would work: (df[col_list].T * df['A']).T but this isn't so pretty Commented Aug 11, 2015 at 18:32

1 Answer 1

1

I never know what do with "most efficient" questions. But if you want that output, you could use mul:

>>> df.loc[:,["D","E"]] = df[["D","E"]].mul(df["A"], axis=0)
>>> df
    A   B   D   E
0   2  12   2   4
1   3  54   3  12
2  10   2  10  10

where you could replace ["D","E"] by list_of_columns so you wouldn't have to repeat the column names.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.