Click here to Skip to main content
15,559,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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


What I have tried:

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
1	A	1	0	0	1
2	B	0	1	0	1
3	C	0	0	3	1
4	D	0	2	0	1


but this did not add the column to df? do I need to add something else? inplace or something? Could you please double check?
Posted
Updated 8-Apr-22 11:36am

1 solution

Not sure what's wrong with your code. I tried to reproduce your issue, but i can't. Below code is working fine:

Python
import pandas as pd

ids1 = [1, 2, 3, 4]
ids2 = ['A', 'B', 'C', 'D']
esc1 = [1, 0, 0, 0]
esc2 = [0, 1, 0, 2]
esc3 = [0, 0, 3, 0]

data = {'ID1': ids1,
    'ID2': ids2,
    'escto1': esc1,
    'escto2': esc2,
    'escto3': esc3}
df = pd.DataFrame(data)
print("Original data:")
print(df)

print("With additional column:")
df['helper'] =  df.filter(like='escto').gt(0).any(1).astype(int)
print(df)


Result:
Original data:
   ID1 ID2  escto1  escto2  escto3
0    1   A       1       0       0
1    2   B       0       1       0
2    3   C       0       0       3
3    4   D       0       2       0
With additional column:
   ID1 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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900