Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading