如何使用2种不同条件在python中过滤数组

时间:2018-07-30 21:55:20

标签: python arrays numpy indexing

我正在尝试创建一个新数组,该数组将由第一列的(数据值<= 20000)以及所有其他对应的列组成。

在数学上,我正在执行以下操作:我正在从文本文件读取数据。我正在寻找到最后一点到所有点的距离。然后,我将仅采用距离小于20000且M1小于11.5的那些行。 数据如下:

# ID M1 M2 M3 M4 R4 M5 R5 x y z
10217 11.467 11.502 13.428 13.599  432.17 13.266  281.06 34972.8 42985.9 14906
7991 11.529 11.559 13.438 13.520  435.23 13.224  272.23 8538.05 33219.8 43375.1
2100 11.526 11.573 13.478 13.490  448.97 13.356  301.27 9371.75 13734.1 43398.6
9467 11.557 11.621 13.481 13.537  449.99 13.367  303.67 33200.3 36008.9 12735.8

我的代码如下:

import numpy as np
import matplotlib.pyplot as plt


halo = 'nntest.txt'
ID, m,r,x,y,z= np.loadtxt(halo, usecols=(0,6,7,8,9,10), unpack =True)



# selet the last point
m_mass = m[-1:]
ID_2 = ID[-1:]
r_2 = r[-1:]
x_2 = x[-1:]
y_2 = y[-1:]
z_2 = z[-1:]

#######################################
#Find distance to all points from our targeted point
nearest_neighbors = []

def neighbors(ID_2, cx,cy,cz, ID, m, r, x, y, z):

    dist = np.sqrt((cx-x)**2 + (cy-y)**2 + (cz-z)**2)

    return dist, ID, m, r, x, y, z

for i in range(len(ID_2)):
    hist = neighbors(ID_2[i], m_2[i], r_2[i], x_2[i], y_2[i], z_2[i], ID, m , r, x, y, z)



    #print all the IDs and all other data which are less than 20000 and M less than 11.5  of that targeted value
    print ID[hist[0]<20000] and m[hist[1]<11.5]

但是我在设置2个条件时遇到问题。它返回此错误:

File "overlaping_halos_finder.py", line 53, in <module>
    combined = zip(ID[hist[0]<r_2[i] and m[hist[1]>1.e12]])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如果不是

print ID[hist[0]<20000] and m[hist[1]<11.5]

我只做:

print ID[hist[0]<20000]

我有以下示例输出:

# ID M R X Y Z
6737.0 909913272632.0 103.06 1988.35 15894.6 40649.0
6617.0 997700063823.0 106.28 1523.55 15433.2 40363.2
6723.0 11 109.91 1993.05 15687.5 40557.2

但是我想摆脱前两个输出,只想打印第3行,其中M列值<11.5

希望可以澄清

您提出的解决此问题的建议将非常有帮助

2 个答案:

答案 0 :(得分:1)

您不需要逻辑and。要打印tuple数组,只需打印以逗号分隔的数组序列即可:

print ID[hist[0]<20000], m[hist[1]<11.5]

ID将由布尔数组hist[0]<20000索引,而m将由布尔数组hist[1]<11.5索引。

如果需要分配给变量,则可以使用序列解压缩:

res1, res2 = ID[hist[0]<20000], m[hist[1]<11.5]

答案 1 :(得分:0)

我不理解您的代码,但是我建议您从标题中定义一个给定一个点的函数,如果应该过滤该点,则返回true。然后,您可以执行以下操作:

def filter_point(point):
    # Conditions over a single point
    # You can read from global variables here, or create a partial function
    # to access external data

    return condition1(point) and condition2(point)

result = filter(filter_point, list_of_points)