简体   繁体   中英

iterate through columns pandas dataframe and create another column based on a condition

I have a dataframe df

ID  ID2 escto1 escto2   escto3
1   A   1   0   0
2   B   0   1   0
3   C   0   0   3
4   D   0   2   0

so either using indexing or using wildcard

like column name 'escto*'
if df.iloc[:, 2:]>0 then df.helper=1

or

df.loc[(df.iloc[:, 3:]>0,'Transfer')]=1

So that output becomes

ID  ID2 escto1  escto2  escto3  helper
1   A   1   0   0   1
2   B   0   1   0   1
3   C   0   0   3   1
4   D   0   2   0   1

Output

One option is to use the boolean output:

df.assign(helper = df.filter(like='escto').gt(0).any(1).astype(int))

   ID ID2  escto1  escto2  escto3  helper
0   1   A       1       0       0       1
1   2   B       0       1       0       1
2   3   C       0       0       3       1
3   4   D       0       2       0       1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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