我有2个ndarray:
a = np.array([[1,2], [5,0], [6,4]])
b = np.array([[1,10],[6,30], [5,20]])
我希望将它们合并为一个数组:
[[ 1 2 10]
[ 5 0 20]
[ 6 4 30]]
有人知道非迭代模式通过列0的值合并2个数组吗?
我只是这样找到的:
import numpy as np
a = np.array([[1,2], [5,0], [6,4]])
b = np.array([[1,10],[6,30], [5,20]])
new0col = np.zeros((a.shape[0],1), dtype=int)
a = np.append(a, new0col, axis=1)
l1 = a[:,0].tolist()
l2 = b[:,0].tolist()
for i in l2:
a[l1.index(i),2] = b[l2.index(i),1]
print(a)
答案 0 :(得分:1)
您可以使用numpy.searchsorted
:
c = np.c_[a, b[np.searchsorted(a[:, 0], b[:, 0]), 1]]
print(c)
array([[ 1, 2, 10],
[ 5, 0, 20],
[ 6, 4, 30]])
首先,请注意应用于b
的行索引为a[:, 0]
中的每个值检索b[:, 0]
的索引:
print(np.searchsorted(a[:, 0], b[:, 0]))
[0 2 1]
答案 1 :(得分:0)
我发现 pandas 的替代解决方案比 numpy 效率低,但我也希望发布,因为我认为这很有启发性。 给我jpp(我不知道该方法)的好解决方案有一个限制, a 和 b 必须具有相同的密钥。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
def merge_w_np(a, b):
zeros = np.zeros((a.shape[0], np.shape(b)[1] -1), dtype=int)
a = np.append(a, zeros, axis=1)
l1 = a[:,0].tolist()
for j, i in enumerate(b[:,0].tolist()):
a[l1.index(i),2] = b[j,1]
print(a)
def merge_w_pd(a, b):
dfa = pd.DataFrame(data=a, # values
index=a[:,0]) # 1st column as index
dfb = pd.DataFrame(data=b, # values
index=b[:,0]) # 1st column as index
dfa.columns = ['id', 'value']
dfb.columns = ['id', 'value']
# print('a',dfa)
# print('b',dfb)
dfc = dfa.merge(dfb, left_on='id', right_on='id', how='outer')
print(dfc)
a = np.array([[1,2], [2,8], [5,0], [6,4], [7,9]])
b = np.array([[1,10],[6,30], [5,20]])
merge_w_np(a, b)
merge_w_pd(a, b)