【发布时间】:2020-01-14 11:58:40
【问题描述】:
我正在尝试以最省时的方式基于某个列合并/加入两个 numpy 数组。
这是我的两个 numpy 数组:
import numpy as np
a1 = np.array([('a', 4.672, 0.999),
('b', 2.24, 0.999),
('c', 1.984, 0.9001),])
a2 = np.array([('a', 4.67),
('c', 2.24)])
这是我的函数,用于返回 与 a2 的第一列匹配的大小为 a1 的行索引。我稍后使用它来制作一个大小相等并连接的数组。所以我需要 a1 的[0, -, 1],它给出了 a2 匹配行的索引。
def find_indices(x, y):
x = x[:, 0]
y = y[:, 0]
index = np.argsort(x)
sorted_x = x[index]
sorted_index = np.searchsorted(sorted_x, y)
yindex = np.take(index, sorted_index, mode="clip")
mask = x[yindex] != y
result = np.ma.array(yindex, mask=mask)
return result
find_indices(a2, a1)
这会返回这个看起来不错的数组。
masked_array(data=[0, --, 1],
mask=[False, True, False],
fill_value=999999)
但是当我使用 masked_array.data 进行切片时,我得到了复制的数据,
a2[idx.data]
array([['a', '4.67'],
['c', '2.24'],
['c', '2.24']], dtype='<U4')
而输出应该是:
array([['a', '4.67'],
-- ,
['c', '2.24']], dtype='<U4')
如何修复这个错误?
【问题讨论】:
标签: python python-3.x numpy numpy-ndarray