【问题标题】:How to add a calculated/computed column in numpy?如何在 numpy 中添加计算/计算列?
【发布时间】:2026-02-16 09:00:01
【问题描述】:

假设我有一个 numpy 数组:

1 10
2 20
3 0
4 30

我想添加第三列,其中每一行是该行前两列的总和(或一些任意计算):

1 10 11
2 20 22
3 0  3
4 30 34

我该怎么做?

【问题讨论】:

    标签: python arrays numpy calculated-columns


    【解决方案1】:

    对于这些类型的计算,内置的map function 非常有用。只需将计算结果添加到第三列即可。求和:

    >>> import numpy as np
    >>> my_arr = np.array([[1, 10], [2, 20], [3, 0], [4, 30]])
    >>> np.vstack( (my_arr.T, map(sum, my_arr) )).T
    array([[ 1, 10, 11],
           [ 2, 20, 22],
           [ 3,  0,  3],
           [ 4, 30, 34]])
    

    它也适用于其他功能:

    >>> my_func = lambda x: 2*x[0] + x[1]
    >>> np.vstack( (my_arr.T, map(my_func, my_arr) )).T
    array([[ 1, 10, 12],
           [ 2, 20, 24],
           [ 3,  0,  6],
           [ 4, 30, 38]])
    

    【讨论】:

    • 出现错误:ValueError: all the input array dimensions except for the concatenation axis must match exactly
    【解决方案2】:
    import numpy
    
    my_arr = numpy.array([[1, 10],
                          [2, 20],
                          [3, 0],
                          [4, 30]])
    column0 = my_arr[:,0:1]  # Use 0:1 as a dummy slice to maintain a 2d array
    column1 = my_arr[:,1:2]  # Use 1:2 as a dummy slice to maintain a 2d array
    new_column = column0 + column1
    my_arr = numpy.hstack((my_arr, new_column))
    

    【讨论】:

      【解决方案3】:

      试试下面的

      注意沿轴 1 的 np.sum 将逐行添加元素。 然后您可以将结果重塑为列矩阵,最后附加到原始数组

      >>> new_col = np.sum(x,1).reshape((x.shape[0],1))
      >>> np.append(x,new_col,1)
      array([[ 1, 10, 11],
             [ 2, 20, 22],
             [ 3, 30, 33],
             [ 4, 40, 44]])
      

      或单行

      np.append(x,np.sum(x,1).reshape((x.shape[0],1)),1)
      

      【讨论】: