[英]How to find an array in string format in pandas using regular expression?
我有一个 csv 文件,其中只包含一个看起来像 df1 的列
Col_A
Name
Address
[B00-OUI_001]
Soemthing else
etc.
另一个有类似的东西。
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]
我试图从 df1 中的 df2 中找出匹配的条目,例如B00-OUI_001
都在 df 中,但在 df2 中它带有_V
,因此它转向正则表达式,因为所有内容都是字符串格式,但在完全匹配中失败。 有人可以帮助我吗?
您可以删除两列中的尾随[]
并使用带元组的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]
另一个想法是通过|
加入独特的价值|
对于正则表达式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]
如果只有“_V”可以破坏精确匹配,为什么不摆脱它并创建一个虚拟列索引? 精确连接总是比任何正则表达式映射的孩子都快。
我的意思是:
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)
输出:
Col_A Col_B
0 [B00-OUI_001] [B00-OUI_001_V]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.