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

如何用Pandas为DataFrame添加非数值转二值的新列

基于非数值条件生成二值列的实现方法

针对你的需求,这里提供几种直接可行的代码写法,都满足以new_df['LN']=开头的要求:

  • 字典映射法(map函数)
    利用map函数通过字典定义映射规则,简洁直观:

    new_df['LN'] = new_df['LN_status'].map({'N1': 1, 'N0': 0})
    
  • 替换法(replace函数)
    replace函数同样支持字典映射,和map实现效果一致:

    new_df['LN'] = new_df['LN_status'].replace({'N1': 1, 'N0': 0})
    
  • 条件判断法(numpy.where)
    如果需要更灵活的条件逻辑,可以使用numpy.where,使用前确保已导入numpy库:

    import numpy as np
    new_df['LN'] = np.where(new_df['LN_status'] == 'N1', 1, 0)
    

由于你提到LN_status列仅包含N1和N0两种取值,上述三种方法都能完美覆盖转换需求,无需额外处理异常情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:21:25