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

Time:04-09

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

CodePudding user response:

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
  • Related