python - 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”方式来归档这个?
解决方案
你很接近 - 需要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
推荐阅读
- vue.js - 将按钮绑定到vue js中for循环内的函数
- javascript - 如何在单击按钮上向此 JavaScript 或 HTML 添加 CSS?
- javascript - 在 javascript 中解析 csv 文件并根据两个特定行提取字典
- wordpress - 网站迁移后的字体问题 - Wordpress
- css - 在 iOS 上双击网站链接的问题
- ruby - 从外部方法跳过 Ruby 迭代器
- git - 如何在目标提交后仅 git push 提交?
- android - 从 ExternalMediaDirs 在 GridView 中显示图像
- php - 如何处理从数据表发送的ajax数据
- javascript - 在 Express 中通过 URL 发送 JSON 数据