简体   繁体   English

基于多列创建新列

[英]Creating a new column based on multiple columns

I'm trying to create a new column based on other columns existing in my df .我正在尝试根据df中存在的其他列创建一个新列。
My new column, col , should be 1 if there is at least one 1 in columns A ~ E.如果 A ~ E 列中至少有一个1 ,我的新列col应该是1
If all values in columns A ~ E is 0 , then value of col should be 0 .如果 A ~ E 列中的所有值都是0 ,那么col的值应该是0
I've attached image for a better understanding.我附上了图片以便更好地理解。

What is the most efficient way to do this with python, not using loop ?使用 python 而不使用loop的最有效方法是什么? Thanks.谢谢。

enter image description here在此处输入图像描述

If need test all columns use DataFrame.max or DataFrame.any with cast to integers for True/False to 1/0 mapping:如果需要测试所有列,请使用DataFrame.maxDataFrame.any为整数以实现True/False1/0映射:

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

Or if need test columns between A:E add DataFrame.loc :或者如果需要A:E之间的测试列添加DataFrame.loc

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

If need specify columns by list use subset:如果需要按列表指定列,请使用子集:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM