![](/img/trans.png)
[英]find the values that ONLY take one value in another column pandas python
[英]Find value in one column in another column with regex in pandas
我有一個包含兩列字符串的pandas數據幀。 我想識別第一列( s1
)中的字符串出現在第二列( s2
)的字符串中的所有行。
所以,如果我的專欄是:
abc abcd*ef_gh
z1y xxyyzz
我想保留第一行,但不是第二行。
我能想到的唯一方法是:
s1
的內容作為匹配模式將df.str.contains()
應用於s2
有沒有辦法實現這一點,不需要迭代行?
它可能是可行的(僅用於簡單匹配),以矢量化方式,使用numpy chararray 方法 :
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
我能想到的最好的方法是使用apply
而不是手動迭代:
>> df = pd.DataFrame({'x': ['abc', 'xyz'], 'y': ['1234', '12xyz34']})
>> df
x y
0 abc 1234
1 xyz 12xyz34
>> df.x[df.apply(lambda row: row.y.find(row.x) != -1, axis=1)]
1 xyz
Name: x, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.