简体   繁体   中英

Is there a way to replace True/False with string values in Pandas?

The pandas data frame looks like this:

     job_url

0    https://neuvoo.ca/view/?id=34134414434
1    https://zip.com/view/?id=35453453454
2    https://neuvoo.com/view/?id=2452444252

I want to turn all the strings beginning with 'https://neuvoo.ca' into 'Canada'.

My solution to this was to search for that using str.startswith and then replacing True with 'Canada'

csv_file['job_url'] = csv_file['job_url'].str.startswith('https://neuvoo.ca/')
csv_file['job_url']  = replace({'job_url': {np.True: 'Canada', np.False: 'USA'}})

But found out that it does't replace boolean with string.

Let's try with np.where instead:

import numpy as np
import pandas as pd

csv_file = pd.DataFrame({
    'job_url': ['https://neuvoo.ca/view/?id=34134414434',
                'https://zip.com/view/?id=35453453454',
                'https://neuvoo.com/view/?id=2452444252']
})


csv_file['job_url'] = np.where(
    csv_file['job_url'].str.startswith('https://neuvoo.ca/'),
    'Canada',
    'USA'
)
  job_url
0  Canada
1     USA
2     USA

replace would work as well but with True and False not np.True / np.False :

csv_file['job_url'] = (
    csv_file['job_url'].str.startswith('https://neuvoo.ca/')
        .replace({True: 'Canada', False: 'USA'})
)

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