簡體   English   中英

Python - 查找多次出現的項目並替換為均值

[英]Python - find items with multiple occurences and replace with mean

對於 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM