【发布时间】:2020-09-20 20:24:02
【问题描述】:
我有一个如下的数据框:
col 1 col 2
0 59 538 Walton Avenue, Chester, FY6 7NP
1 62 42 Chesterton Road, Peterborough, FR7 2NY
2 179 3 Wallbridge Street, Essex, 4HG 3HT
3 180 6 Stevenage Avenue, Coventry, 7PY 9NP
列表类似于:
[Stevenage, Essex, Coventry, Chester]
按照此处的解决方案:How to check if Pandas rows contain any full string or substring of a list? 如下所示:
city_list = list(cities["name"])
df["col3"] = np.where(df["col2"].str.contains('|'.join(city_list)), df["col2"], '')
我发现 col 2 中的一些匹配列表中的字符串,但 col3 与 col2 相同。我希望 col3 成为列表中的值,而不是与 col3 相同。这将是:
col 1 col 2 col3
0 59 538 Walton Avenue, Chester, FY6 7NP Chester
1 62 42 Chesterton Road, Peterborough, FR7 2NY
2 179 3 Wallbridge Street, Essex, 4HG 3HT Essex
3 180 6 Stevenage Avenue, Coventry, 7PY 9NP Coventry
我试过了:
pat = "|".join(cities.name)
df.insert(0, "name", df["col2"].str.extract('(' + pat + ')', expand = False))
但这会返回一个错误,说 456 个输入,而预期为 1。
还有:
df["col2"] = df["col2"].apply(lambda x: difflib.get_close_matches(x, cities["name"])[0])
df.merge(cities)
但这回来时错误列表索引超出范围。
有没有办法做到这一点? df1 大约有 160,000 个条目,col2 中的每个地址来自不同国家,因此没有标准的书写方式,而城市列表大约有 170,000 个条目
谢谢
【问题讨论】:
-
到目前为止你尝试过什么?给我们看一些代码