python - Python - 查找多次出现的项目并用平均值替换
问题描述
对于 df:
sample type count
sample1 red 5
sample1 red 7
sample1 green 3
sample2 red 2
sample2 green 8
sample2 green 8
sample2 green 2
sample3 red 4
sample3 blue 5
我想在“类型”中查找多次出现的项目,并将每个项目的“计数”替换为平均计数。所以预期的输出:
sample type count
sample1 red 6
sample1 green 3
sample2 red 2
sample2 green 6
sample3 red 4
sample3 blue 5
所以
non_uniq = df.groupby("sample")["type"].value_counts()
non_uniq = non_uniq.where(non_uniq > 1).dropna()
找到多次出现的“类型”,但我不知道如何在 df 中匹配它
解决方案
我相信您可以简化mean
每个组的解决方案,因为值的平均值与此值相同:
df = df.groupby(["sample","type"], as_index=False, sort=False)["count"].mean()
print (df)
sample type count
0 sample1 red 6
1 sample1 green 3
2 sample2 red 2
3 sample2 green 6
4 sample3 red 4
5 sample3 blue 5
您的解决方案可以通过以下方式更改:
m = df.groupby(["sample", "type"])['type'].transform('size') > 1
df1 = df[m].groupby(["sample","type"], as_index=False, sort=False)["count"].mean()
df = pd.concat([df1, df[~m]], ignore_index=True)
print (df)
sample type count
0 sample1 red 6
1 sample2 green 6
2 sample1 green 3
3 sample2 red 2
4 sample3 red 4
5 sample3 blue 5
推荐阅读
- performance - 以下嵌套循环中第二个 for 循环的时间复杂度是多少?
- unix - 查找在同一行上多次出现模式的文件
- javascript - 用java脚本添加零小数
- amazon-web-services - EventType:查看器请求导致 503 的 lambda 边缘
- c++ - 如何使用 boost/beast 从 HTTP POST 请求中解析和提取有效负载?
- julia - 在 Julia 中初始化任何变量
- nestjs - 如何在 NestJS 上测试具有多个守卫的控制器
- linux - 我们如何从 ELF 二进制文件或编译器生成的元数据中获取指针的位置
- java - 线程输出错误
- c# - 通过我的 ajax 调用调用操作结果并在新窗口上成功后重新发布