如何使用 np.where() 创建特定行的新数组?

How to use np.where() to create a new array of specific rows?

我有一个包含 1700 个值的数组 (msaarr),范围从大约 0 到 150。我知道其中 894 个值应该小于 2,我希望创建一个仅包含这些值的新数组。

到目前为止,我已经尝试过此代码:

Combined = np.zeros(shape=(894,8))

for i in range(len(Spitzer)):         #len(Spitzer) = 1700
    index = np.where(msaarr <= 2)
    Combined[:,0] = msaarr[index]

之所以有八列,是因为我有更多与 msaarr 中每个值关联的数据,我也想显示这些数据。 msaarr 是使用几行代码创建的,这就是为什么我没有在这里提及它们,但它是一个形状为 (1700,1) 且类型为 float64 的数组。

我遇到的问题是,如果我打印 msaarr[index],那么我会得到一个形状为 (893,) 的数组,但是当我尝试将其分配为我的第零列时,我得到错误

ValueError: could not broadcast input array from shape (1699) into shape (894)

我也尝试过

Combined[:,0] = np.extract(msaarr <= 2, msaarr)

同样的错误。

起初我认为这可能只是与 Python 的零索引有些混淆,所以我尝试将形状更改为 893,并尝试分配给不同的列 Combined[:,1 ], 但我每次都出现同样的错误。

或者,当我尝试时:

Combined[:,1][i] = msaarr[index][i]

我收到错误:

IndexError: index 894 is out of bounds for axis 0 with size 894

我做错了什么?

编辑:

有朋友指出我可能没有正确调用索引,因为它是一个元组,所以他的建议是:

index = np.where(msaarr < 2)
Combined[:,0] = msaarr[index[0][:]]

但我仍然收到此错误:

ValueError: could not broadcast input array from shape (893,1) into shape (893)

我的形状怎么可能是 (893) 而不是 (893, 1)?

另外,我查了一下,len(index[0][:]) = 893, len(msaarr[index[0][:]]) = 893.

最后一次尝试的完整代码是:

import numpy as np
from astropy.io import ascii
from astropy.io import fits

targets = fits.getdata('/Users/vcolt/Dropbox/ATLAS source matches/OzDES.fits')
Spitzer = ascii.read(r'/Users/vcolt/Desktop/Catalogue/cdfs_spitzer.csv', header_start=0, data_start=1)

## Find minimum separations, indexed.
RADiffArr = np.zeros(shape=(len(Spitzer),1))
DecDiffArr = np.zeros(shape=(len(Spitzer),1))
msaarr = np.zeros(shape=(len(Spitzer),1))
Combined= np.zeros(shape=(893,8))

for i in range(len(Spitzer)):
    x = Spitzer["RA_IR"][i]
    y = Spitzer["DEC_IR"][i]
    sep = abs(np.sqrt(((x - targets["RA"])*np.cos(np.array(y)))**2 + (y - targets["DEC"])**2))
    minsep = np.nanmin(sep)
    minseparc = minsep*3600
    msaarr[i] = minseparc
    min_positions = [j for j, p in enumerate(sep) if p == minsep]
    x2 = targets["RA"][min_positions][0]
    RADiff = x*3600 - x2*3600
    RADiffArr[i] = RADiff
    y2 = targets["DEC"][min_positions][0]
    DecDiff = y*3600 - y2*3600
    DecDiffArr[i] = DecDiff

index = np.where(msaarr < 2)
print msaarr[index].shape
Combined[:,0] = msaarr[index[0][:]]

无论 index = np.where(msaarr < 2) 是否在循环中,我都会得到同样的错误。

我认为循环不在正确的位置。 np.where() 将 return 与您指定的条件匹配的元素索引数组。

这应该足够了

Index = np.where(msaarr <= 2)

因为索引是一个数组。您需要遍历此索引并填充 combined[:0]

中的值

另外我想指出一件事。您说过会有 894 个值小于 2,但在代码中您使用的是小于等于 2。

看看 numpy.takenumpy.where 结合使用。

inds = np.where(msaarr <= 2)
new_msaarr = np.take(msaarr, inds)

如果是多维数组,还可以加上axis关键字,沿该轴取片

np.where(condition) 将 return 一个数组元组,其中包含验证您的条件的元素的索引。
要获取验证条件的元素数组,请使用:

new_array = msaarr[msaarr <= 2]
>>> x = np.random.randint(0, 10, (4, 4))
>>> x
array([[1, 6, 8, 4],
       [0, 6, 6, 5],
       [9, 6, 4, 4],
       [9, 6, 8, 6]])
>>> x[x>2]
array([6, 8, 4, 6, 6, 5, 9, 6, 4, 4, 9, 6, 8, 6])