[英]Merging two NumPy 2D array
I am trying to merge/join two numpy array based on some column in the most time-efficient way.我正在尝试以最省时的方式合并/加入基于某些列的两个 numpy 数组。
Here are my two numpy arrays:这是我的两个 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)])
Here is my function to return an array of size a1's rows of indices matching on a2's first column .这是我的函数,用于返回大小为 a1 的索引行与 a2 的第一列匹配的数组。 I use this later to make an array of equal size and concatenate.
我稍后使用它来制作一个大小相等的数组并进行连接。 So I need
[0, -, 1]
for a1 which gives the index of matching rows of a2.所以我需要
[0, -, 1]
for a1 它给出了 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)
This returns this array which seems good.这将返回这个看起来不错的数组。
masked_array(data=[0, --, 1],
mask=[False, True, False],
fill_value=999999)
but when I slice using masked_array.data, I get replicated data,但是当我使用 masked_array.data 切片时,我得到了复制的数据,
a2[idx.data]
array([['a', '4.67'],
['c', '2.24'],
['c', '2.24']], dtype='<U4')
whereas the output should be:而输出应该是:
array([['a', '4.67'],
-- ,
['c', '2.24']], dtype='<U4')
How to fix this bug?如何修复这个错误?
Finally, I found the solution:最后,我找到了解决方案:
idx = find_indices(a2, a1)
d = a2[idx]
d[idx.mask] = np.nan
merged_array = np.concatenate((a1, d), axis=1)
I use the mask to replace the duplicated values with Nan.我使用掩码用 Nan 替换重复的值。 Then directly concatenate.
然后直接连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.