首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Pandas -如何进行分组,其中新列的结果是(列的总和)/(分组的iten数)?

在Pandas中,可以使用groupby()函数进行分组操作,并结合transform()函数计算新列的结果。具体步骤如下:

  1. 导入Pandas库:import pandas as pd
  2. 创建一个DataFrame对象,假设为df
  3. 使用groupby()函数按照需要分组的列进行分组,例如按照group_col列进行分组:grouped = df.groupby('group_col')
  4. 使用transform()函数结合自定义的计算函数对分组后的数据进行计算,例如计算列sum_col的总和并除以分组的项数:result = grouped['sum_col'].transform(lambda x: x.sum() / len(x))

完整的代码示例如下:

代码语言:txt
复制
import pandas as pd

# 创建DataFrame对象
df = pd.DataFrame({
    'group_col': ['A', 'A', 'B', 'B', 'B'],
    'sum_col': [1, 2, 3, 4, 5]
})

# 分组并计算新列
grouped = df.groupby('group_col')
result = grouped['sum_col'].transform(lambda x: x.sum() / len(x))

# 将结果添加到原DataFrame中
df['new_col'] = result

# 打印结果
print(df)

输出结果为:

代码语言:txt
复制
  group_col  sum_col  new_col
0         A        1      1.5
1         A        2      1.5
2         B        3      4.0
3         B        4      4.0
4         B        5      4.0

在这个例子中,我们按照group_col列进行分组,然后计算sum_col列的总和并除以分组的项数,将结果存储在新的列new_col中。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券