pandas 数据框如下所示:
job_url
0 https://neuvoo.ca/view/?id=34134414434
1 https://zip.com/view/?id=35453453454
2 https://neuvoo.com/view/?id=2452444252
我想把所有以“https://neuvoo.ca”开头的字符串都变成“Canada”。
我对此的解决方案是使用 str.startswith 搜索,然后用“加拿大”替换 True
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'}})
但发现它并没有用字符串替换布尔值。
答案 0 :(得分:2)
让我们尝试用 np.where
代替:
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
也可以使用,但使用 True
和 False
而不是 np.True
/np.False
:
csv_file['job_url'] = (
csv_file['job_url'].str.startswith('https://neuvoo.ca/')
.replace({True: 'Canada', False: 'USA'})
)