【问题标题】:How to append element to array in python [duplicate]如何在python中将元素附加到数组[重复]
【发布时间】:2019-08-13 13:00:06
【问题描述】:

我有两个数组 XYX 的大小为 (5000,2351),Y 的大小为 (2351,)。我对Y 使用了reshape 函数来获取大小(1,2351)。然后我使用附加函数到X,而不是大小(5001,2351)我得到(117552351,)。

Y = Y.reshape(1,-1)
X = np.append(X,Y)

哪里出了问题?

【问题讨论】:

  • 你需要一个简单的np.vstack([X,Y])
  • np.concatenate

标签: python arrays numpy append


【解决方案1】:

你可以使用np.concatenate:

X = np.arange(0,15).reshape(5,3)
Y = np.arange(0,3)
Y = Y.reshape(1,-1)

np.concatenate([X,Y])

产量:

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14],
       [ 0,  1,  2]])

【讨论】:

    【解决方案2】:

    来自https://docs.scipy.org/doc/numpy-1.14.2/reference/generated/numpy.append.html

    如果axis为None,则out为扁平数组 你应该使用axis=0,或者更好地使用vstack()

    numpy.append(arr, values, axis=None)[source]
    Append values to the end of an array.
    
    Parameters: 
    arr : array_like
    
    Values are appended to a copy of this array.
    
    values : array_like
    
    These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.
    
    axis : int, optional
    
    The axis along which values are appended. If axis is not given, both arr and values are flattened before use.
    
    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-23
      • 2013-10-05
      • 1970-01-01
      • 2020-11-01
      • 2017-04-16
      • 2012-08-30
      • 2014-05-26
      • 1970-01-01
      相关资源
      最近更新 更多