5

I have a DataFrame (df), with the following columns:

cols = ['A','B','C','D']

How can I multiply the values in these columns to form a single column called 'VAL'?

I can do this: df['VAL'] = df['A']*df['B']*df['C']*df['D']

But this will not scale; I want to use the cols variable to multiply these columns together.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
user308827
  • 21,227
  • 87
  • 254
  • 417

2 Answers2

8

Select the columns in the list using loc and then use .prod() across the rows (by specifying axis=1). For example:

>>> cols = ['A','B','C','D']
>>> df = pd.DataFrame(np.random.randint(1, 4, size=(3,4)), columns=list('ABCD'))
>>> df
   A  B  C  D
0  2  2  1  1
1  2  3  1  1
2  3  1  3  3

>>> df['VAL'] = df.loc[:, cols].prod(axis=1)
>>> df
   A  B  C  D  VAL
0  2  2  1  1    4
1  2  3  1  1    6
2  3  1  3  3   27
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • axis =1 meaning that we iterate across columns? – user308827 Oct 05 '15 at 20:59
  • 1
    @user308827: that's correct - `axis=1` means perform the method across the columns of the DataFrame. – Alex Riley Oct 05 '15 at 21:08
  • thanks @ajcr, makes sense. I do see in several places, axis=1 for operations across rows. – user308827 Oct 05 '15 at 21:12
  • 1
    No problem, glad I could help. The `axis` thing can take a little while to get used to in pandas: [here's an answer](http://stackoverflow.com/a/25774395/3923281) I wrote a little while ago explaining which axis refers to what. – Alex Riley Oct 05 '15 at 21:14
-1

I'm assuming that you want the product so that, for every row, you have the product of a,b, c and d for that row.

You can use the apply method:

df['VAL'] = df.apply(lambda x: x.A * x.B * x.C * x.D, axis=1)

elelias
  • 4,552
  • 5
  • 30
  • 45