所以我有一个看起来像这样的df:
Created UserID Service
1/1/2016 a CWS
1/2/2016 a Other
3/5/2016 a Drive
2/7/2017 b Enhancement
... ... ...
我想根据"服务"中的值来过滤它。 CWS和Drive的列。我是这样做的:
df=df[(df.Service=="CWS") or (df.Service=="Drive")]
它无法正常工作。有什么想法吗?
答案 0 :(得分:3)
需要与|
(or
)进行比较:
df=df[(df.Service=="CWS") | (df.Service=="Drive")]
更好的是使用isin
:
df=df[(df.Service.isin(["CWS", "Drive")]])
或使用query
:
df = df.query('Service=="CWS" | Service=="Drive"')
df = df.query('Service== ["Other", "Drive"]')
print (df)
Created UserID Service
1 1/2/2016 a Other
2 3/5/2016 a Drive
答案 1 :(得分:1)
您也可以使用pandas.Series.str.match
df[df.Service.str.match('CWS|Drive')]
Created UserID Service
0 1/1/2016 a CWS
2 3/5/2016 a Drive
其他口味
好玩!!
<强> numpy
强> -fi
s = df.Service.values
c1 = s == 'CWS'
c2 = s == 'Drive'
df[c1 | c2]
添加numexpr
import numexpr as ne
s = df.Service.values
c1 = s == 'CWS'
c2 = s == 'Drive'
df[ne.evaluate('c1 | c2')]
<强>时序强>
isin
是赢家! str.match
是输家: - (
np.random.seed([3,1415])
df = pd.DataFrame(dict(
Service=np.random.choice(['CWS', 'Drive', 'Other', 'Enhancement'], 100000)))
%timeit df[(df.Service == "CWS") | (df.Service == "Drive")]
%timeit df[df.Service.isin(["CWS", "Drive"])]
%timeit df.query('Service == "CWS" | Service == "Drive"')
%timeit df.query('Service == ["Other", "Drive"]')
%timeit df.query('Service in ["Other", "Drive"]')
%timeit df[df.Service.str.match('CWS|Drive')]
100 loops, best of 3: 16.7 ms per loop
100 loops, best of 3: 4.46 ms per loop
100 loops, best of 3: 7.74 ms per loop
100 loops, best of 3: 5.77 ms per loop
100 loops, best of 3: 5.69 ms per loop
10 loops, best of 3: 67.3 ms per loop
%%timeit
s = df.Service.values
c1 = s == 'CWS'
c2 = s == 'Drive'
df[c1 | c2]
100 loops, best of 3: 5.47 ms per loop
%%timeit
import numexpr as ne
s = df.Service.values
c1 = s == 'CWS'
c2 = s == 'Drive'
df[ne.evaluate('c1 | c2')]
100 loops, best of 3: 5.65 ms per loop