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”方法来实现这个?


眼眸繁星
浏览 105回答 1
1回答

精慕HU

您很接近 - 需要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.duplicatedwithkeep=False来返回所有重复项的掩码:df["recoded"] = np.where(df["col1"].duplicated(keep=False), df["col1"], "other")print (df)0     1     1       11     1     3       12     1     2       13     2     4       24     2     6       25     3     5   other6     4     7   other
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python