【问题标题】:How to add column to numpy array如何将列添加到numpy数组
【发布时间】:2013-04-04 15:47:10
【问题描述】:

我正在尝试将一列添加到从recfromcsv 创建的数组中。在本例中,它是一个数组:[210,8] (rows, cols)。

我想添加第九列。空或带零无关紧要。

from numpy import genfromtxt
from numpy import recfromcsv
import numpy as np
import time

if __name__ == '__main__':
 print("testing")
 my_data = recfromcsv('LIAB.ST.csv', delimiter='\t')
 array_size = my_data.size
 #my_data = np.append(my_data[:array_size],my_data[9:],0)

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

【问题讨论】:

  • 这有什么不好的?
  • 不起作用的是,无论我尝试什么版本,它都没有给我正确的尺寸。

标签: python numpy


【解决方案1】:

我认为您的问题是您希望 np.append 就地添加列,但由于 numpy 数据的存储方式,它的作用是创建连接数组的副本

Returns
-------
append : ndarray
    A copy of `arr` with `values` appended to `axis`.  Note that `append`
    does not occur in-place: a new array is allocated and filled.  If
    `axis` is None, `out` is a flattened array.

所以你需要保存输出all_data = np.append(...):

my_data = np.random.random((210,8)) #recfromcsv('LIAB.ST.csv', delimiter='\t')
new_col = my_data.sum(1)[...,None] # None keeps (n, 1) shape
new_col.shape
#(210,1)
all_data = np.append(my_data, new_col, 1)
all_data.shape
#(210,9)

替代方式:

all_data = np.hstack((my_data, new_col))
#or
all_data = np.concatenate((my_data, new_col), 1)

我相信这三个函数(以及np.vstack)之间的唯一区别是它们在未指定axis 时的默认行为:

  • concatenate 假设 axis = 0
  • hstack 假定 axis = 1 除非输入是 1d,否则 axis = 0
  • vstack 如果输入为 1d,则在添加轴后假定 axis = 0
  • append 展平数组

根据您的评论,并更仔细地查看您的示例代码,我现在相信您可能想要做的是将一个 字段 添加到 record array。您同时导入了genfromtxt,它返回一个structured arrayrecfromcsv,它返回一个微妙不同的record array (recarray)。您使用了recfromcsv,所以现在my_data 实际上是recarray,这意味着很可能my_data.shape = (210,) 因为recarrays 是一维记录数组,其中每条记录都是具有给定dtype 的元组。

所以你可以试试这个:

import numpy as np
from numpy.lib.recfunctions import append_fields
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
data = np.array( list(zip(x,y,z)), dtype=[('x',float),('y',float),('z',float)])
data = np.recarray(data.shape, data.dtype, buf=data)
data.shape
#(10,)
tot = data['x'] + data['y'] + data['z'] # sum(axis=1) won't work on recarray
tot.shape
#(10,)
all_data = append_fields(data, 'total', tot, usemask=False)
all_data
#array([(0.4374783740738456 , 0.04307289878861764, 0.021176067323686598, 0.5017273401861498),
#       (0.07622262416466963, 0.3962146058689695 , 0.27912715826653534 , 0.7515643883001745),
#       (0.30878532523061153, 0.8553768789387086 , 0.9577415585116588  , 2.121903762680979 ),
#       (0.5288343561208022 , 0.17048864443625933, 0.07915689716226904 , 0.7784798977193306),
#       (0.8804269791375121 , 0.45517504750917714, 0.1601389248542675  , 1.4957409515009568),
#       (0.9556552723429782 , 0.8884504475901043 , 0.6412854758843308  , 2.4853911958174133),
#       (0.0227638618687922 , 0.9295332854783015 , 0.3234597575660103  , 1.275756904913104 ),
#       (0.684075052174589  , 0.6654774682866273 , 0.5246593820025259  , 1.8742119024637423),
#       (0.9841793718333871 , 0.5813955915551511 , 0.39577520705133684 , 1.961350170439875 ),
#       (0.9889343795296571 , 0.22830104497714432, 0.20011292764078448 , 1.4173483521475858)], 
#      dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8'), ('total', '<f8')])
all_data.shape
#(10,)
all_data.dtype.names
#('x', 'y', 'z', 'total')

【讨论】:

  • 获取文件“d:\python27\lib\site-packages\numpy\core_methods.py”,第 18 行,in _sum out=out,keepdims=keepdims) TypeError: cannot perform reduce with flexible type
  • @user2130951 你的阵列的dtype 是什么? my_data.dtype
  • @user2130951 确定不想添加字段
【解决方案2】:

如果你有一个数组,a,比如 210 行乘 8 列:

a = numpy.empty([210,8])

如果想添加第九列零,您可以这样做:

b = numpy.append(a,numpy.zeros([len(a),1]),1)

【讨论】:

  • 这会生成 return concatenate((arr, values), axis=axis) ValueError: all the input array must have the same number of dimensions
  • 嗯。只是仔细检查了一下。它对我有用(使用 IDLE - python 2.7 版)
  • 也许是因为,正如@askewchan 所建议的那样,您实际上有重载?我认为如果您使用numpy.genfromtxtnumpy.loadtxt 导入,这会起作用?
  • 如果列的形状是 (X, ) 那么你必须 .reshape(X, 1) 来应用追加。这是用 data[:,1] 提取列后的情况
  • 这适用于我使用 python 3.5,但是,是的,使用它时必须小心形状。
【解决方案3】:

最简单的解决方案是使用 numpy.insert()

np.insert() 相对于np.append 的优势在于您可以将新列插入到自定义索引中。

import numpy as np

X = np.arange(20).reshape(10,2)

X = np.insert(X, [0,2], np.random.rand(X.shape[0]*2).reshape(-1,2)*10, axis=1)
'''

【讨论】:

  • 最后reshape部分发生了什么?
【解决方案4】:

np.appendnp.hstack 期望附加的列是正确的形状,即 N x 1。我们可以使用 np.zeros 创建这个 zeros 列(或 np.ones 创建一个 one 列)并附加它到我们的原始矩阵(二维数组)。

def append_zeros(x):
    zeros = np.zeros((len(x), 1))  # zeros column as 2D array
    return np.hstack((x, zeros))   # append column

【讨论】:

    【解决方案5】:

    我以这种方式向矩阵数组添加一个新列:

    Z = append([[1 for _ in range(0,len(Z))]], Z.T,0).T
    

    也许效率不高?

    【讨论】:

    • 不要使用列表解析,使用np.onesnp.ones_like: append([np.ones_like(Z)], Z.T, 0).T
    【解决方案6】:

    可以这样做:

    import numpy as np
    
    # create a random matrix:
    A = np.random.normal(size=(5,2))
    
    # add a column of zeros to it:
    print(np.hstack((A,np.zeros((A.shape[0],1)))))
    

    一般来说,如果A是一个m*n矩阵,并且需要添加一列,则必须创建一个n*1的零矩阵,然后使用“hstack”将零矩阵添加到右边矩阵 A。

    【讨论】:

      【解决方案7】:

      类似于建议使用numpy.hstack 的其他一些答案,但更具可读性:

      import numpy as np
      
      # declare 10 rows x 3 cols integer array of all 1s
      arr = np.ones((10, 3), dtype=np.int64)
      
      # get the number of rows in the original array (as if we didn't know it was 10 or it could be different in other cases)
      numRows = arr.shape[0]
      # declare the new array which will be the new column, integer array of all 0s so it's visually distinct from the original array
      additionalColumn = np.zeros((numRows, 1), dtype=np.int64)
      
      # use hstack to tack on the additionl column
      result = np.hstack((arr, additionalColumn))
      
      print(result)
      

      结果:

      $ python3 scratchpad.py 
      [[1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]
       [1 1 1 0]]
      

      【讨论】:

        猜你喜欢
        • 2021-07-16
        • 2010-12-26
        • 2014-03-05
        • 2017-07-03
        • 1970-01-01
        • 2012-06-21
        • 2016-02-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多