![](/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.