How can I change multiple values in one column that contain specific substring in pandas?

Question:

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?

Asked By: Sofia693

||

Answers:

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
Answered By: Scott Boston

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
Answered By: BrokenBenchmark
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.