You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas中将DataFrame指定列转换为0/1二值的问题求解

问题根因

pandas的where()方法的执行逻辑为:条件为真时保留原始值,条件为假时替换为传入的默认值。
你编写的代码crm['Reconciled'].where(crm['Reconciled'] > 0, 1)实际执行逻辑和需求完全相反:

  • 当Reconciled值>0时,保留原值(1~130的数值)
  • 当Reconciled值<=0时(即你需要保留的原值0),被替换为1
    所以最终整列所有值都变成了1。

正确实现方案

提供3种常用实现方式,任选其一即可:

方案1:修正where条件逻辑

调整判断条件,让原值为0时保留原值,其余替换为1:

crm['Reconciled'] = crm['Reconciled'].where(crm['Reconciled'] == 0, 1)

方案2:布尔值转整数(最简洁)

非0数值转布尔值为True,0转布尔值为False,直接转整数就天然符合需求:

crm['Reconciled'] = crm['Reconciled'].astype(bool).astype(int)

方案3:使用numpy.where(可读性更高)

numpy的where方法参数逻辑更直观:np.where(条件, 条件成立返回值, 条件不成立返回值)

import numpy as np
crm['Reconciled'] = np.where(crm['Reconciled'] == 0, 0, 1)

内容的提问来源于stack exchange,提问作者user15235239

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:36:07