数据框架Python的复杂条件

时间:2017-11-03 05:14:30

标签: python python-3.x

我有以下数据框

X y z count 1 1 1 2 1 1 2 1 1 3 1 4 2 2 2 100 2 7 5 1 3 3 7 6 4 7 3 9

x,y和z是坐标,它们都是唯一的。

我想要检索包含count> = threshold或其邻居count> = threshold的点。

我使用了以下代码

`df=df[(df["count"]>=theta) | (df[df["X"]+1>=theta]) |
                              (df[df["X"]+2>=theta]) | 
                              (df[df["X"]+3>=theta]) |
                              (df[df["X"]-1>=theta]) |
                              (df[df["X"]-2>=theta]) |
                              (df[df["X"]-3>=theta]) |
                              (df[df["y"]+1>=theta]) |
                              (df[df["y"]+2>=theta]) | 
                              (df[df["y"]+3>=theta]) |
                              (df[df["y"]-1>=theta]) |
                              (df[df["y"]-2>=theta]) |
                              (df[df["y"]-3>=theta]) |
                              (df[df["z"]+1>=theta]) |
                              (df[df["z"]+2>=theta]) | 
                              (df[df["z"]+3>=theta]) |
                              (df[df["z"]-1>=theta]) |
                              (df[df["z"]-2>=theta]) |
                              (df[df["z"]-3>=theta])]
`

但是这段代码不起作用。我的问题是,当我在当前行上时,在其他行上形成条件,以及如何对xy或{{中的下一个和上一个点执行条件1}} coordinates.I想检查第三个邻居。 `移'也许可以完成这项工作,但我不明白它是如何运作的。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:首先选择所有带有计数> = theta with

的行
df1 = df[df["count"] >= theta]

接下来遍历df1行并检查关闭点是否有计数< THETA 在df。这看起来像这样。

temp = [df1]
for ind,row in df1.iterrows():
    temp.append(df[(df["X"] == row["X"]+1) & (df["count"] < theta)])
df_final = pd.concat(temp)

在这里你可以根据需要添加更多条件,看看我正在寻找计数&lt; theta作为更大的那些已经在df1数据帧中。最后一行将列表中的所有数据帧合并为一个。

这使得访问另一行变得不必要。

  • 请注意,我没有对代码进行测试,因此语法可能需要调整,但这个想法是我想传达的。