简体   繁体   中英

Applying a function to columns in a dataframe whose column headings contain a specific string

I have a dataframe called passenger_details which is shown below

Passenger     Age  Gender   Commute_to_work    Commute_mode    Commute_time ...
Passenger1    32   Male      I drive to work      car              1 hour
Passenger2    26   Female    I take the metro     train            NaN    ...
Passenger3    33   Female      NaN                 NaN             30 mins      ...
Passenger4    29   Female    I take the metro     train            NaN     ...
...

I want to apply an if function that will turn missing values(NaN values) to 0 and present values to 1, to column headings that have the string 'Commute' in them.

This is basically what I'm trying to achieve

Passenger     Age  Gender   Commute_to_work    Commute_mode    Commute_time ...
Passenger1    32   Male         1                 1              1
Passenger2    26   Female       1                 1              0    ...
Passenger3    33   Female       0                 0              1      ...
Passenger4    29   Female       1                 1              0     ...
...

However, I'm struggling with how to phrase my code. This is what I have done

passenger_details = passenger_details.filter(regex = 'Location_', axis = 1).apply(lambda value: str(value).replace('value', '1', 'NaN','0'))

But I get a Type Error of

'replace() takes at most 3 arguments (4 given)'

Any help would be appreciated

Seelct columns by Index.contains and test not missing values by DataFrame.notna and last cast to integer for True/False to 1/0 map:

c = df.columns.str.contains('Commute')
df.loc[:, c] = df.loc[:, c].notna().astype(int)
print (df)
    Passenger  Age  Gender  Commute_to_work  Commute_mode  Commute_time
0  Passenger1   32    Male                1             1             1
1  Passenger2   26  Female                1             1             0
2  Passenger3   33  Female                0             0             1
3  Passenger4   29  Female                1             1             0

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