I have a pandas DataFrame where a column contains several strings:
sample_df =
cars
0 BMW
1 Honda
2 Porshe
3 BMWLuxury
4 TeslaLuxury
5 Ford
6 Ferrari
7 PorsheLuxury
I would like to change the value in column "cars" that contains substring "Luxury" with 1 and others with 0. How can I achieve this?
CodePudding user response:
Try this:
df['cars'] = df['cars'].str.contains('Luxury').astype('int')
Output:
0 0
1 0
2 0
3 1
4 1
5 0
6 0
7 1
Name: cars, dtype: int32
CodePudding user response:
You can use:
df["cars"] = df["cars"].str.contains("Luxury").astype(int)
This outputs:
cars
0 0
1 0
2 0
3 1
4 1
5 0
6 0
7 1