首页 > 解决方案 > 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 中匹配它

标签: pythonpandas

解决方案


我相信您可以简化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

推荐阅读