使用Python处理pandas DataFrame的power列 非0/1值统一设为0
方法1:pandas where 方法(最简洁)
直接对power列做条件筛选,不符合要求的值直接替换为0:
data_A['power'] = data_A['power'].where(data_A['power'].isin([0, 1]), other=0)
方法2:布尔索引赋值
定位所有非0、非1的异常值行,直接赋值为0,逻辑更直观:
# ~ 为逻辑取反,筛选出所有不在[0,1]范围内的行 data_A.loc[~data_A['power'].isin([0, 1]), 'power'] = 0
方法3:numpy where 实现(大数据量下性能更优)
data_A['power'] = np.where(data_A['power'].isin([0, 1]), data_A['power'], 0)
处理完成后可以用以下代码验证结果是否符合预期:
print(data_A['power'].unique()) # 预期输出只有 [0, 1] 两个值
内容的提问来源于stack exchange,提问作者Lee
相关产品推荐
相关产品推荐

