【问题标题】:How to append a column to a 2d numpy array in Python 2.7?如何在 Python 2.7 中将列附加到 2d numpy 数组?
【发布时间】:2017-11-22 20:15:33
【问题描述】:

我有两个 numpy 数组。一种是具有 3 列和 4 行的二维矩阵。第二个 numpy 数组是具有 4 个值的一维数组。有没有办法将第二个 numpy 数组作为列附加到 Python 2.7 中的第一个 numpy 数组?

例如,如果这是我的两个 numpy 数组:

arr2d = np.matrix(
[[1, 2, 3],
[4, 5, 6], 
[7, 8, 9], 
[10, 11, 12]])

column_to_add = np.array([10, 40, 70, 100])

我希望输出看起来像这样

    [[1, 2, 3, 10],
    [4, 5, 6, 40], 
    [7, 8, 9, 70], 
    [10, 11, 12, 100]]

我尝试过使用

output = np.hstack((arr2d, column_to_add))

但我收到一条错误消息:

ValueError: all the input arrays must have the same number of dimensions. 

我们不胜感激。非常感谢!

【问题讨论】:

  • 更正维数:np.concatenate((arr2d, column_to_add[:,None]), axis=1)[:,None] 将一维数组变成二维列数组。

标签: python arrays python-2.7 numpy


【解决方案1】:

你可以使用numpy.column_stack:

import numpy as np

arr2d = np.matrix(
[[1, 2, 3],
[4, 5, 6], 
[7, 8, 9], 
[10, 11, 12]])

column_to_add = np.array([10, 40, 70, 100])

output = np.column_stack((arr2d, column_to_add))

输出:

matrix([[  1,   2,   3,  10],
        [  4,   5,   6,  40],
        [  7,   8,   9,  70],
        [ 10,  11,  12, 100]])

【讨论】:

    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多