1

我有一个数据框如下,

df2 = pd.DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                    'c' : np.random.randn(7)})

我想从 df2 中选择“a”列等于“二”或“三”的数据,我的代码如下,

df2[df2['a']=='two'or df2['a']=='three']

谁能告诉我为什么我的代码不起作用?

错误:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

提前致谢!

4

3 回答 3

2

就是它isin

slice=df2.loc[df2.a.isin(['one','two'])].copy()
slice
Out[797]: 
     a  b         c
0  one  x -0.064378
1  one  y  0.344902
2  two  y -0.080087
4  two  y  1.433515
5  one  x  1.065794
于 2019-05-14T00:29:16.450 回答
1

使用|代替or

df2[(df2['a']=='two') | (df2['a']=='three')]
于 2019-05-13T23:51:53.117 回答
0

你很接近但你需要做一些事情,首先使用|运算符指定一个或语句,其次将每个条件放在括号中,

这应该工作

df2.loc[(df2['a']=='two') | (df2['a']=='three')]

于 2019-05-13T23:54:41.583 回答