Pandas: Product of specific columns

雨燕双飞 提交于 2019-12-14 03:48:06

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/21167478/pandas-product-of-specific-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!