[英]How to check if a substring in a pandas dataframe column exists in a substring of another column in the same dataframe?
I have a dataframe with columns like this:我有一个包含如下列的数据框:
A B
0 - 5923FoxRd 5923 Fox Rd
1 631 Newhaven Ave Modesto
2 Saratoga Street, Suite 200 Saratoga Street, Suite 200
I want to create a list with values from A that matches values from B. The list should look like [- 5923FoxRd, Saratoga Street, Suite 200...].我想创建一个列表,其中包含与 B 中的值匹配的 A 值。该列表应类似于 [- 5923FoxRd, Saratoga Street, Suite 200...]。 What is the easiest way to do this?
什么是最简单的方法来做到这一点?
To make a little go a long way, do the following:要使一点点走很长的路,请执行以下操作:
\\W+
to str.replace()
\\W+
传递给str.replace()
str.lower()
str.lower()
drive
to dr
, avenue
to ave
, etc.drive
规范化为dr
, avenue
为ave
等。s1 = df['A'].str.replace('\W+', '').str.lower()
s2 = df['B'].str.replace('\W+', '').str.lower()
lst = [*df[s1==s2]['A']]
lst
Out[1]: ['- 5923FoxRd', 'Saratoga Street, Suite 200']
This is what s1
and s2
look like:这是
s1
和s2
样子:
print(s1,s2)
0 5923foxrd
1 631newhavenave
2 saratogastreetsuite200
Name: A, dtype: object
0 5923foxrd
1 modesto
2 saratogastreetsuite200
Name: B, dtype: object
From there, you might want to create some replace values in order to normalize your data even further like:从那里,您可能想要创建一些替换值以进一步规范化您的数据,例如:
to_replace = ['drive', 'avenue', 'street']
replaced = ['dr', 'ave', 'str']
to_replace = ['drive', 'avenue', 'street']
replaced = ['dr', 'ave', 'str']
s1 = df['A'].str.replace('\W+', '').str.lower().replace(to_replace, replaced, regex=True)
s2 = df['B'].str.replace('\W+', '').str.lower().replace(to_replace, replaced, regex=True)
lst = [*df[s1==s2]['A']]
lst
print(s1,s2)
0 5923foxrd
1 631newhavenave
2 saratogastrsuite200
Name: A, dtype: object
0 5923foxrd
1 modesto
2 saratogastrsuite200
Name: B, dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.