![](/img/trans.png)
[英]Add the values of a panda dataframe column if the value of another column is the same
[英]Add values in column of Panda Dataframe
我想将特定列的值相加。 我有一个从CSV加载的数据框,其中包含以下数据:
Date Item Count Price per Unit Sales
0 1/21/16 Unit A 40 $1.50 $60.00
1 1/22/16 Unit A 20 $1.50 $30.00
2 1/23/16 Unit A 100 $1.50 $150.00
我想把所有的销售额加起来。 我试过了:
print sales_df.groupby(["Sales"]).sum()
但这并没有增加销售额。 我该怎么做才能使这项工作?
IIUC,您需要对“ Sales
列中的值求和。 首先,你需要删除$
与str.replace
,然后转换为数值与pd.to_numeric
。 然后,您可以使用sum
。 一班轮:
pd.to_numeric(df.Sales.str.replace("$", "")).sum()
并逐步:
In [35]: df.Sales
Out[35]:
0 $60.00
1 $30.00
2 $150.00
Name: Sales, dtype: object
In [36]: df.Sales.str.replace("$", "")
Out[36]:
0 60.00
1 30.00
2 150.00
Name: Sales, dtype: object
In [37]: pd.to_numeric(df.Sales.str.replace("$", ""))
Out[37]:
0 60
1 30
2 150
Name: Sales, dtype: float64
In [38]: pd.to_numeric(df.Sales.str.replace("$", "")).sum()
Out[38]: 240.0
注意 : pd.to_numeric
仅适用于pandas
版本> = 0.17.0
。 如果您使用的是旧版本,请查看convert_object(convert_numeric=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.