首页 > 解决方案 > Pandas - 根据 value_counts() 结果重新编码变量

问题描述

这是我的数据框:

df = pd.DataFrame({'col1': [1, 1, 1, 2, 2, 3, 4], 
                   'col2': [1, 3, 2, 4, 6, 5, 7]})

我尝试根据它们在我的数据集中出现的频率来重新编码值,在这里我想将每个只出现一次的值重新标记为“其他”。这是所需的输出:

#desired
"col1": [1,1,1,2,2,"other", "other"]

我试过了,但没有奏效:

df["recoded"] = np.where(df["col1"].value_counts() > 1, df["col1"], "other")

我的想法是保存值计数并过滤它们,然后遍历结果数组,但这似乎过于复杂。有没有一种简单的“pythonic/pandas”方式来归档这个?

标签: pythonpandas

解决方案


你很接近 - 需要Series.map与原版相同长度的系列DataFrame

df["recoded"] = np.where(df["col1"].map(df["col1"].value_counts()) > 1, df["col1"], "other")

或通过以下GroupBy.transform方式与计数值一起使用GroupBy.size

df["recoded"] = np.where(df.groupby('col1')["col1"].transform('size') > 1, 
                         df["col1"], 
                         "other")

如果需要检查重复项,请使用Series.duplicated所有keep=False重复项的返回掩码:

df["recoded"] = np.where(df["col1"].duplicated(keep=False), df["col1"], "other")

print (df)
0     1     1       1
1     1     3       1
2     1     2       1
3     2     4       2
4     2     6       2
5     3     5   other
6     4     7   other

推荐阅读