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

标签 python arrays indexing extract where-clause

我有一个包含 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

我做错了什么?

编辑:

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

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) 是在循环内还是循环外,我都会遇到相同的错误。

最佳答案

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

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

如果是多维数组,还可以添加axis关键字沿该轴进行切片。

关于python - 如何使用 np.where() 创建特定行的新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35859789/

相关文章:

c++ - 如何在 C++ 中有效地访问数组的多个元素?

database - 按降序索引日期列是个好主意吗?

python - 在 Pandas DataFrame 中构建多重索引

Python - 如何仅复制新修改的文​​件

python - 使用 pyside 中的 QWizard 下一个插槽

c - 算法(!=线性搜索)在整数数组中查找第一个小于 X 的数字

c# - 尝试在 linux 中运行 spark 作业来解析第六列上的大量制表符分隔数据和索引。获取权限被拒绝

python - 在 Python 连接期间与 MySQL 服务器失去连接

python - 使用 python 切片 CSV 中的特定字符

arrays - 如何计算 Delphi 中 JSON 数组中元素的数量