arrays - 合并两个 numpy 数组

标签 arrays python-3.x numpy merge

我正在尝试合并具有相同数量参数的两个数组。

输入:

first = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775],
         [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745],
         [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745]]

second = [[1],
          [2],
          [3]]

我的预期输出:
final = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775, 1],
             [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745, 2],
             [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745, 3]]

为此,我创建了简单的循环:
for i in first:
        for j in second:
            final += np.append(j, i)

我得到了我补充说我错过了一些东西。首先我的循环我非常慢。其次,我的数据有超过 200 万行要循环。所以我试图找到更快的方法,例如使用以下代码:
final = [np.append(i, second[0]) for i in first] 

它的工作速度比前一个循环快得多,但它只附加第二个数组的第一个值。
你能帮助我吗?

最佳答案

使用 np.array然后 np.concatenate ,

import numpy as np

first = np.array([[650001.88, 300442.2,   18.73,  0.575,  
                   650002.094, 300441.668, 18.775],
                  [650001.96, 300443.4,   18.7,   0.65,   
                   650002.571, 300443.182, 18.745],
                  [650002.95, 300442.54,  18.82,  0.473,  
                   650003.056, 300442.085, 18.745]])

second = np.array([[1],
                   [2],
                   [3]])

np.concatenate((first, second), axis=1)

哪里axis=1意味着我们要水平连接。

这对我行得通

关于arrays - 合并两个 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43561622/

相关文章:

python - 两个列表列表之间的公共(public)元素(嵌套列表的交集)

python - 将二维数组(字段)添加到 numpy recarray

arrays - 计算lua中字符串索引表的数量

ios - 迭代视频数组 iOS

python - 无法为 `pip` 安装 `python 3.3` 但对于 `python 2.7` 工作正常

python - 为什么 __init__ 显然是可选的?

python-3.x - Pandas系列垂直合并

python - 在 python 中使用 numpy 获取避免 nan 的平均值

java - 如果您尝试在完整数组中排队,循环数组是否会覆盖当前数字?

python - python中解压缩和乘法稀疏数组的有效方法