基于使用python在另一列中查找字符来更改列的值

2024-06-08 22:36:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含“城市”和“国家”列的数据集。一些国家/地区栏被错误地标记为“其他”。我之所以知道这一点,是因为一些城市值包含诸如鞍湖(加拿大)之类的标签。是否有一种方法可以搜索城市中的值子集以更改国家/地区中的值。IE搜索任何包含单词“Canada”的城市值,并将country更改为“Canada”。我想为包括美国和英国在内的多个国家做这件事。这可能意味着我的搜索将需要一个'或'元素和搜索美国,美国,美国等

当前数据集:

City - Country
Saddle(Canada) - Other
Dublin - Other
Detroit - USA
Vancouver - Canada
NYC: US - Other

输出:

Saddle(Canada) - Canada
Dublin -Other
Detroit - USA
Vancouver - Canada
NYC: US - USA

我尝试了一些示例代码,但不起作用:

for index, row in df.iterrows():
    if row['city'].str.contains("anada"):
        df.loc[index, 'country'] = "Canada"

Tags: 数据index国家country地区rowusother
1条回答
网友
1楼 · 发布于 2024-06-08 22:36:04

这是一种您可以尝试的高级方法。根据数据集的脏程度,它可能有用,但归根结底,这是一个NLP/AI问题

# using regular expressions _may_ make your life easier
import re

# these regex are for entertainment purposes only
# no warranty of efficacy or fitness for any specific purpose is implied
country_patterns = {
  "Canada" : re.compile(r'canada'),
  "USA": re.compile(r'(usa)|(us)|(united states)|(united states of america|america)'),
  "Japan": re.compile(r'(japan)|(nihon)',
   # etc...
}

for index, row in df.iterrows():
   # a double loop now, so we can check each country pattern against the city
   for country, pattern in country_patterns.items()
       # ignoring the case will simplify creating the regular expressions
       if re.match(pattern, row['city'], re.IGNORECASE):
           df.loc[index, 'country'] = country
           # move on to the next row, since we found a match
           break

您必须创建自己的正则表达式,这可能会成为它自己的一个难题

相关问题 更多 >