[英]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.