[英]How to find an array in string format in pandas using regular expression?
I have a csv file which contains only one column that looks like this df1我有一个 csv 文件,其中只包含一个看起来像 df1 的列
Col_A
Name
Address
[B00-OUI_001]
Soemthing else
etc.
and another that has something like this.另一个有类似的东西。
df2 df2
Col_B
[B00-OUI_000_V]
[B00-OUI_002_V]
[B00-OUI_003_V]
[B00-OUI_001_V]
[B00-OUI_005_V]
[B00-OUI_006_V]
[B00-OUI_007_V]
I am trying to find out matching entries from df2 in df1 like B00-OUI_001
is in both df but in df2 its with _V
, so it turned to regular expression as everything is in string format, but have been failing in exact match.我试图从 df1 中的 df2 中找出匹配的条目,例如B00-OUI_001
都在 df 中,但在 df2 中它带有_V
,因此它转向正则表达式,因为所有内容都是字符串格式,但在完全匹配中失败。 Can someone help me in this?有人可以帮助我吗?
You can remove trailing []
in both columns and filter with Series.str.startswith
with tuples:您可以删除两列中的尾随[]
并使用带元组的Series.str.startswith
过滤:
tups = tuple(df1['Col_A'].str.strip('[]').unique())
df2 = df2[df2['Col_B'].str.strip('[]').str.startswith(tups)]
print (df2)
Col_B
3 [B00OUI_001_V]
Another idea is join unique values by |
另一个想法是通过|
加入独特的价值|
for regex OR
and use Series.str.contains
:对于正则表达式OR
并使用Series.str.contains
:
v = '|'.join(df1['Col_A'].str.strip('[]').unique())
df2 = df2[df2['Col_B'].str.strip('[]').str.contains(v)]
print (df2)
Col_B
3 [B00OUI_001_V]
If it's only "_V" that can disrupt exact match, why not get rid of it and create a dummy column index?如果只有“_V”可以破坏精确匹配,为什么不摆脱它并创建一个虚拟列索引? Exact join always will be faster than any kid of regex-mapping.精确连接总是比任何正则表达式映射的孩子都快。
What I mean:我的意思是:
df2["Col_B_edt"]=df2["Col_B"].str.replace("_V]", "]")
df3=pd.merge(df,df2,left_on="Col_A",right_on="Col_B_edt").drop("Col_B_edt", axis=1)
Output:输出:
Col_A Col_B
0 [B00-OUI_001] [B00-OUI_001_V]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.