【问题标题】:Pandas - How to make a groupment in which a new column is the result of (sum of a column)/(number of itens grouped)?Pandas - 如何进行分组,其中新列是(一列的总和)/(分组的数量)的结果?
【发布时间】:2019-06-07 02:20:12
【问题描述】:

我需要进行某种分组,其中新列(结果)是值列的总和除以找到的项目数?有人可以帮帮我吗?

例如:

表 A

+-------+------+
| item  | value|
+-------+------+
| x     |  100 |
| y     |  200 |
| y     |  400 | 
+-------+------+

正确结果:

表 B

+-------+-----------+
| item  | result    |
+-------+-----------+
| x     | 100/1     |
| y     |(200+400)/2|
+-------+-----------+

代码:

d = {'item': ['x', 'y', 'y'], 'value': [100,200,400]}
df = pd.DataFrame(data=d)
df

【问题讨论】:

  • df.groupby(['item']).apply(lambda x: x['value'].sum()/len(x))

标签: pandas pandas-groupby sklearn-pandas pandasql


【解决方案1】:

你可以使用DataFrameGroupBy.agg:

s = df.groupby('item')['value'].agg(lambda x: x.sum()/len(x)) 
print (s)
item
x    100
y    300
Name: value, dtype: int64

或将GroupBy.sumGroupBy.size 分开:

g = df.groupby('item')['value']
s = g.sum() / g.size()
print (s)
item
x    100.0
y    300.0
Name: value, dtype: float64

但是sum/sizemean,所以解决方案应该简化为GroupBy.mean

s = df.groupby('item')['value'].mean()
print (s)
item
x    100
y    300
Name: value, dtype: int64

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2021-10-30
    • 2012-07-14
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多