用 Pandas 中的多个字符串替换一个字符串
Replace a string with a string out of many in Pandas
所以,我有一个 pandas 数据框,其中一列包含用户国籍的描述,我想用他来自的国家/地区替换整个描述。
我输入的是 df 和国家列表:
Description
ID
I am from Atlantis
1
My family comes from Narnia
2
["narnia","uzbekistan","Atlantis",...]
我知道:
- 我每个描述只有一个国家
- 描述中是否包含国家名称,没有必要从他说的推断国家,我只想将[phrase containing name of country]映射到[country]。
如果我只有一个国家可以替换,我可以使用类似
的东西
df.loc[df['description'].str.contains('Atlantis', case=False), 'description'] = 'Atlantis'
我知道,因为国家/地区名称是在列表中组织的,所以我可以循环浏览它并将其应用于所有元素,例如:
for country in country_list:
df.loc[df['description'].str.contains(country, case=False), 'description'] = country
但在我看来 unpythonic 所以我想知道是否有人可以帮助我找到更好的方法(我确定存在)
输出应该是:
Description
ID
Atlantis
1
Narnia
2
您可以使用 pd.Series.str.extract
:
country_list = ["narnia","uzbekistan","Atlantis"]
df = pd.DataFrame({'Description': {0: 'I am from Atlantis',
1: 'My family comes from Narnia'},
'ID': {0: 1, 1: 2}})
print (df["Description"].str.extract(f"({'|'.join(country_list)})", flags=re.I))
0
0 Atlantis
1 Narnia
所以,我有一个 pandas 数据框,其中一列包含用户国籍的描述,我想用他来自的国家/地区替换整个描述。
我输入的是 df 和国家列表:
Description | ID |
---|---|
I am from Atlantis | 1 |
My family comes from Narnia | 2 |
["narnia","uzbekistan","Atlantis",...]
我知道:
- 我每个描述只有一个国家
- 描述中是否包含国家名称,没有必要从他说的推断国家,我只想将[phrase containing name of country]映射到[country]。
如果我只有一个国家可以替换,我可以使用类似
的东西df.loc[df['description'].str.contains('Atlantis', case=False), 'description'] = 'Atlantis'
我知道,因为国家/地区名称是在列表中组织的,所以我可以循环浏览它并将其应用于所有元素,例如:
for country in country_list:
df.loc[df['description'].str.contains(country, case=False), 'description'] = country
但在我看来 unpythonic 所以我想知道是否有人可以帮助我找到更好的方法(我确定存在)
输出应该是:
Description | ID |
---|---|
Atlantis | 1 |
Narnia | 2 |
您可以使用 pd.Series.str.extract
:
country_list = ["narnia","uzbekistan","Atlantis"]
df = pd.DataFrame({'Description': {0: 'I am from Atlantis',
1: 'My family comes from Narnia'},
'ID': {0: 1, 1: 2}})
print (df["Description"].str.extract(f"({'|'.join(country_list)})", flags=re.I))
0
0 Atlantis
1 Narnia