在 pandas 中使用正则表达式在另一列中的一列中查找值 [英] Find value in one column in another column with regex in pandas
本文介绍了在 pandas 中使用正则表达式在另一列中的一列中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有两列字符串的pandas数据框.我想确定第一列(s1
)中的字符串出现在第二列(s2
)中的所有行.
I have a pandas dataframe with two columns of strings. I want to identify all row where the string in the first column (s1
) appears within the string in the second column (s2
).
所以,如果我的专栏是:
So if my columns were:
abc abcd*ef_gh
z1y xxyyzz
我想保留第一行,而不是第二行.
I want to keep the first row, but not the second.
我唯一想到的方法是:
- 遍历数据框行
- 使用
s1
的内容作为匹配模式将df.str.contains()
应用于s2
- iterate through dataframe rows
- apply
df.str.contains()
tos2
using the contents ofs1
as the matching pattern
是否有一种不需要遍历行的方法来实现此目的?
Is there a way to accomplish this that doesn't require iterating over the rows?
推荐答案
使用numpy chararray,以向量化的方式可能可行(仅用于简单匹配)
It is probably doable (for simple matching only), in a vectorised way, with numpy chararray methods:
In [326]:
print df
s1 s2
0 abc abcd*ef_gh
1 z1y xxyyzz
2 aaa aaabbbsss
In [327]:
print df.ix[np.char.find(df.s2.values.astype(str),
df.s1.values.astype(str))>=0,
's1']
0 abc
2 aaa
Name: s1, dtype: object
这篇关于在 pandas 中使用正则表达式在另一列中的一列中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文