Question

Finding the product of all columns in a dataframe is easy:

df['Product'] = df.product(axis=1)

How can I specify which column names (not column numbers) to include in the product operation?

From the help page for DataFrame.product(), I am not sure whether it is possible.

Was it helpful?

Solution

You can use the df[[colname1, colname2, colname3...]] syntax to select the columns you want and then call .product on that:

>>> df = pd.DataFrame({"A": [2,2], "B": [3,3], "C": [5,5]})
>>> df
   A  B  C
0  2  3  5
1  2  3  5

[2 rows x 3 columns]
>>> df[["A", "C"]].product(axis=1)
0    10
1    10
dtype: int64
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top