如何使用列的值在一个ndarray上合并2个numpy ndarray?

2024-09-30 06:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2个月:

a = np.array([[1,2], [5,0], [6,4]])
b = np.array([[1,10],[6,30], [5,20]])

我希望将它们合并成一个数组,如下所示:

^{pr2}$

有人知道用列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)

Tags: importnumpyl1indexasnp模式zeros
2条回答

您可以使用^{}

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的行索引为b[:, 0]中的每个值检索{}的索引:

^{pr2}$

我发现了另一种解决方法,用熊猫来解决问题,效率不如小熊猫,但我也希望贴出来,因为我认为这很有启发性。 给我jpp(我不知道这个方法)的好的解决方案有一个限制,ab必须有相同的键。在

#!/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)

相关问题 更多 >

    热门问题