【问题标题】:Creating a new column based on multiple columns基于多列创建新列
【发布时间】:2021-12-06 14:54:18
【问题描述】:

我正在尝试根据df 中现有的其他列创建一个新列。
如果 A ~ E 列中至少有一个 1,我的新列 col 应该是 1
如果 A ~ E 列中的所有值都是0,那么col 的值应该是0
我附上了图片以便更好地理解。

不使用loop,使用python 执行此操作的最有效方法是什么?谢谢。

enter image description here

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果需要测试所有列,请使用 DataFrame.maxDataFrame.any 并将 True/False 转换为整数以进行 1/0 映射:

    df['col'] = df.max(axis=1)
    df['col'] = df.any(axis=1).astype(int)
    

    或者如果需要A:E之间的测试列添加DataFrame.loc:

    df['col'] = df.loc[:, 'A':'E'].max(axis=1)
    df['col'] = df.loc[:, 'A':'E'].any(axis=1).astype(int)
    

    如果需要通过列表指定列使用子集:

    cols = ['A','B','C','D','E']
    df['col'] = df[cols].max(axis=1)
    df['col'] = df[cols].any(axis=1).astype(int)
    

    【讨论】:

    • 考虑到 OP 的示例数据,我在想 df['col'] = df['A':'E'].max(axis=1) 可能是一个选项
    • @JonClements - 谢谢,loc 没有必要?
    • @JonClements - 经过测试,您的解决方案返回 TypeError: cannot do slice indexing on RangeIndex with these indexers [A] of type str, loc 是必要的
    • 是的......现在是早上 7 点,我已经工作了一夜...... :)
    • @JonClements - 欧,我建议如果可能的话去睡觉;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 2018-08-09
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多