2016-08-22 43 views
-1

这看起来很简单,但我似乎无法弄清楚。我知道如何过滤熊猫数据框到符合条件的所有行,但是当我想要相反的时候,我总是收到奇怪的错误。在不符合条件的所有行上过滤熊猫数据框

这里是例子。 (背景:一个简单的棋盘游戏,其中作品是在网格上,我们正在试图给它一个坐标,并返回所有相邻块,但不是实际的实际工件坐标)

import pandas as pd 
import numpy as np 

df = pd.DataFrame([[5,7, 'wolf'], 
       [5,6,'cow'], 
       [8, 2, 'rabbit'], 
       [5, 3, 'rabbit'], 
       [3, 2, 'cow'], 
       [7, 5, 'rabbit']], 
       columns = ['lat', 'long', 'type']) 

coords = [5,7] #the coordinate I'm testing, a wolf 

view = df[((coords[0] - 1) <= df['lat']) & (df['lat'] <= (coords[0] + 1)) \ 
    & ((coords[1] - 1) <= df['long']) & (df['long'] <= (coords[1] + 1))] 

view = view[not ((coords[0] == view['lat']) & (coords[1] == view['long'])) ] 

print(view) 

我以为not应该否定随后括号内的布尔值,但这似乎不是它的工作原理。

我希望它能够在5,6的时候返回牛,但不是5,7的狼(因为这是当前的作品)。只是为了仔细检查我的逻辑,我做了

me = view[(coords[0] == view['lat']) & (coords[1] == view['long'])] 
print(me) 

并且这只是回报狼,正如我所料。那么,为什么我不能只把not放在那个前面,并得到其他一切呢?或者,更重要的是,我该如何去做其他事情。

回答

1

由于numpy(因此pandas)使用按位运算符,所以应该用代替not。这也是您使用&而不是and的原因。

import pandas as pd 

df = pd.DataFrame({'a': [1, 2]}) 

print(df[~(df['a'] == 1)]) 
>> a 
    1 2 

和使用例如:

import pandas as pd 
import numpy as np 

df = pd.DataFrame([[5,7, 'wolf'], 
       [5,6,'cow'], 
       [8, 2, 'rabbit'], 
       [5, 3, 'rabbit'], 
       [3, 2, 'cow'], 
       [7, 5, 'rabbit']], 
       columns = ['lat', 'long', 'type']) 

coords = [5,7] #the coordinate I'm testing, a wolf 

view = df[((coords[0] - 1) <= df['lat']) & (df['lat'] <= (coords[0] + 1)) \ 
    & ((coords[1] - 1) <= df['long']) & (df['long'] <= (coords[1] + 1))] 

view = view[~ ((coords[0] == view['lat']) & (coords[1] == view['long'])) ] 

print(view) 
>> lat long type 
    1 5  6 cow 
+0

是的!谢谢。我也尝试过使用'!',因为我认为这样的事情可能会发生,但我还是有点偏离。再次感谢。 – seth127