简体   繁体   English

如何对与pandas DataFrame中另一列的特定值对应的列值求和?

[英]How can I sum column values that corrispond to a specific value of another column in a pandas DataFrame?

I have a python pandas DataFrame with (item,feature,grade) 我有一个带有(item,feature,grade)的python pandas DataFrame

item feature grade
1    1       0.8
1    2       0.3
2    1       0.6
...

and I have to sum all grade values for each same item, so for example 而且我必须对每个相同项目的所有成绩值求和,例如

for item 1 sum of grade is 1.1

and I have to put all the sum in a new DataFrame with (item,sumGrade): 并且我必须将所有总和放入带有(item,sumGrade)的新DataFrame中:

item sumGrade
1    1.1
2    0.6
...

How can I do this without using groupby and apply function? 不使用groupby和apply函数怎么办? Because I need a good performance in computation. 因为我需要良好的计算性能。

Thank you 谢谢

You can groupby on 'item' column and then call sum on the 'grade' column, additionally call reset_index to restore the 'item' column back: 您可以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

Not sure why you don't want to group but you can also set the index to 'item' and sum on the index level: 不确定为什么不希望分组,但也可以将索引设置为“ 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.

相关问题 如何根据熊猫中另一列的底值将一列中的值求和? - How can I sum the values in one column based on the floor'd value of another column in pandas? 如何在 pandas dataframe 的另一列中添加计数特定值的计数器列? - How can I add a counter column that counts specific values in another column in a pandas dataframe? 使用 Pandas 将特定列值替换为另一个数据框列值 - Replace specific column values with another dataframe column value using Pandas 根据熊猫数据框中的另一列值计算值的总和? - Calculate the sum of values based on another column value in pandas dataframe? 如何编写 Python 代码来查找特定行值的 Pandas DF 中列的值的总和? - How can I write the Python code to find the sum of values of a column in a Pandas DF for a specific row value? Pandas dataframe,如何按多列分组并为特定列应用总和并添加新的计数列? - Pandas dataframe, how can I group by multiple columns and apply sum for specific column and add new count column? 如何在特定日期范围内对熊猫列DataFrame中的某些值求和 - How to sum certain values in a pandas column DataFrame in a specific date range 如何对熊猫数据框进行分组并对另一列中的值求和 - How to groupby pandas dataframe and sum values in another column 如何对照另一个列检查pandas数据框列的值并在第三列中操作该值 - How can I check the value of a pandas dataframe column against another column and manipulate the value in a third column 如何将 pandas dataframe 中的列值作为新的键值对添加到具有字典的另一列中? - How can I add column values from a pandas dataframe as a new key value pair in another column having dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM