![](/img/trans.png)
[英]How can I sum the values in one column based on the floor'd value of another column in pandas?
[英]How can I sum column values that corrispond to a specific value of another column in a pandas DataFrame?
我有一個帶有(item,feature,grade)的python pandas DataFrame
item feature grade
1 1 0.8
1 2 0.3
2 1 0.6
...
而且我必須對每個相同項目的所有成績值求和,例如
for item 1 sum of grade is 1.1
並且我必須將所有總和放入帶有(item,sumGrade)的新DataFrame中:
item sumGrade
1 1.1
2 0.6
...
不使用groupby和apply函數怎么辦? 因為我需要良好的計算性能。
謝謝
您可以groupby
在“項目”一欄,然后調用sum
對“品位”專欄,還叫reset_index
恢復“項”列回:
In [10]:
df.groupby(['item'])['grade'].sum().reset_index()
Out[10]:
item grade
0 1 1.1
1 2 0.6
不確定為什么不希望分組,但也可以將索引設置為“ item”並在索引級別sum
:
In [11]:
df.set_index('item')['grade'].sum(level=0)
Out[11]:
item
1 1.1
2 0.6
Name: grade, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.