Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Product of specific columns

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.

like image 732
Zhubarb Avatar asked Jan 16 '14 16:01

Zhubarb


People also ask

How do I get a list of unique values from a column in pandas?

You can get unique values in column (multiple columns) from pandas DataFrame using unique() or Series. unique() functions. unique() from Series is used to get unique values from a single column and the other one is used to get from multiple columns.

What does explode do in pandas?

Pandas DataFrame explode() Method The explode() method converts each element of the specified column(s) into a row.

How do pandas Series multiply?

The mul() method of the pandas Series multiplies the elements of one pandas Series with another pandas Series returning a new Series. Multiplying of two pandas. Series objects can be done through applying the multiplication operator “*” as well.


1 Answers

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
like image 90
DSM Avatar answered Sep 30 '22 18:09

DSM