如何在Pandas DataFrame中按指定条件创建0-1新列?
解决方案
方法一:利用逻辑表达式直接推导
观察规则可发现,新列的值等价于col1与col2是否为正的结果不相等,用这个逻辑生成新列最简洁:
import pandas as pd # 构造示例数据 df = pd.DataFrame({ 'col1': [0, 0, 1, 1, 1], 'col2': [2, -4, -2, 5, 9] }) # 生成新列 df['new_colum'] = (df['col1'] != (df['col2'] > 0)).astype(int)
运行后结果完全匹配示例:
col1 col2 new_colum 0 0 2 1 1 0 -4 0 2 1 -2 1 3 1 5 0 4 1 9 0
方法二:使用np.where显式匹配规则
如果更倾向于直观对应每条规则,可用嵌套np.where:
import numpy as np df['new_colum'] = np.where( df['col1'] == 0, np.where(df['col2'] > 0, 1, 0), np.where(df['col2'] < 0, 1, 0) )
该写法完全对应你列出的规则:
- 当col1为0时,col2为正设1,为负设0
- 当col1为1时,col2为负设1,为正设0
方法三:自定义函数+apply(不推荐大数据集)
若需灵活扩展逻辑,可使用自定义函数配合apply,但效率较低,不适合大样本:
def get_new_col(row): if row['col1'] == 0: return 1 if row['col2'] > 0 else 0 else: return 1 if row['col2'] < 0 else 0 df['new_colum'] = df.apply(get_new_col, axis=1)
内容的提问来源于stack exchange,提问作者user15649753
相关产品推荐
相关产品推荐

