![](/img/trans.png)
[英]select rows from a DataFrame based on column value, limit to 16384 rows
[英]Select rows from dataframe based on substring A or B in a column
抱歉,由於我實際上正在查找具有多個字符的子字符串,因此我需要編輯問題。 建議的答案很好,但大多數情況下只適用於一個字符串。
import panda as pd
test = pd.DataFrame({'A': 'ju1 j4 abjul boy noc s1 asep'.split(),
'B': [1, 2, 3, 4, 5, 6, 7]})
print(test)
A B
0 ju1 1
1 j4 2
2 abjul 3
3 boy 4
4 noc 5
5 s1 6
6 asep 7
我知道我可以選擇所有包含'ju'的行
subset = test[test['A'].str.contains('ju')]
print(subset)
A B
0 ju1 1
1 abjul 3
有沒有一種優雅的方法來選擇所有包含'ju'或'as'的行?
如下所示,這可行,還有其他方法也可行嗎?
ju = test.A.str.contains('ju')
as = test.A.str.contains('as')
subset = test[ju | as]
In [13]: test.loc[test.A.str.contains(r'[js]')]
Out[13]:
A B
0 j1 1
1 j4 2
2 abjul 3
5 s1 6
6 asep 7
選項1
嘗試使用str.match
test[test.A.str.match('.*[js].*')]
選項2
set
操作
s = test.A.apply(set)
test[s.sub(set(list('js'))).lt(s)]
選項3
通過numpy
廣播set
操作
s = test.A.apply(set)
test[(~(np.array([[set(['j'])], [set(['s'])]]) - s.values).astype(bool)).any(0)]
選項4
分開的條件
cond_j = test.A.str.contains('j')
cond_s = test.A.str.contains('s')
test[cond_j | cond_s]
所有產量
A B
0 j1 1
1 j4 2
2 abjul 3
5 s1 6
6 asep 7
時間測試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.