如何用Pandas将DataFrame中出现频率最高的列值转为1,其余转为0?
Pandas实现将高频取值转为1、其余转为0
核心思路
先定位目标列中出现频率最高的取值,再通过条件判断将匹配值转为1,其余转为0。
具体代码实现
假设你的DataFrame名为df,目标列名为target_col:
1. 获取出现频率最高的取值
两种常用方式:
- 方式一:通过
value_counts()取频率最高的索引
most_common = df['target_col'].value_counts().index[0]
- 方式二:用
mode()直接获取众数(更简洁)
most_common = df['target_col'].mode()[0]
2. 生成0/1标记列
可以选择生成新列或覆盖原列:
- 生成新列(推荐,保留原始数据)
# 方法1:用numpy的where函数 import numpy as np df['flag_col'] = np.where(df['target_col'] == most_common, 1, 0) # 方法2:布尔值转整数(更简洁) df['flag_col'] = (df['target_col'] == most_common).astype(int)
- 直接替换原列
df['target_col'] = (df['target_col'] == most_common).astype(int)
示例效果
假设原始数据列是:
| target_col |
|---|
| 苹果(30%) |
| 香蕉(50%) |
| 香蕉(50%) |
| 橙子(20%) |
| 香蕉(50%) |
处理后flag_col结果:
| flag_col |
|---|
| 0 |
| 1 |
| 1 |
| 0 |
| 1 |
内容的提问来源于stack exchange,提问作者Lokesh Rathi
相关产品推荐
相关产品推荐

