Adding elements to an array and assigning it to same object

时间:2018-03-22 23:37:20

标签: python arrays numpy

I have an array that looks like this.

array([[ 1],
       [ 5],
       [ 3],
       [ 4],
       [10]])

I need to iterate through each of the element in the array and create this

[1 1]
[5 2]
[3 3]
[4 4]
[10  5]

I am able to print it this way using the following code:

for i in range(len(arr2)): 
    print(np.append(arr2[i],i+1))

But I am not able to append this new element on the actual array itself. When I try to assign np.append(arr2[i],i+1) to arr2[i], it throws an error.

for i in range(len(arr2)): 
        arr2[i]=np.append(arr2[i],i+1)

I get this error

ValueError: could not broadcast input array from shape (2) into shape (1)

2 个答案:

答案 0 :(得分:2)

For practical matters, the size of a numpy array is fixed.

That said, there is a resize method, but it has a couple of restrictions:

1) It does not have ND semantics:

>>> x = np.array([[ 1], [ 5], [ 3], [ 4], [10]])
>>> 
>>> x.resize((5, 2))
>>> 
>>> x
array([[ 1,  5],
       [ 3,  4],
       [10,  0],
       [ 0,  0],
       [ 0,  0]])

2) It often does not work:

>>> x = np.array([[ 1], [ 5], [ 3], [ 4], [10]])
>>> 
>>> x
array([[ 1],
       [ 5],
       [ 3],
       [ 4],
       [10]])
>>> 
>>> x.resize((5, 2))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot resize an array that references or is referenced
by another array in this way.  Use the resize function

3) Where it works it often allocates a new data buffer:

>>> x = np.array([[ 1], [ 5], [ 3], [ 4], [10]])
>>> 
>>> x.ctypes.data
30384064
>>> 
>>> x.resize((5, 2))
>>> 
>>> x.ctypes.data
31463392

So you are probably better off creating a new object:

>>> x = np.array([[ 1], [ 5], [ 3], [ 4], [10]])
>>> np.c_[x, 1:6]
array([[ 1,  1],
       [ 5,  2],
       [ 3,  3],
       [ 4,  4],
       [10,  5]])

If you absolutely want the new data in the old object you could do something like

>>> x = np.array([[ 1], [ 5], [ 3], [ 4], [10]])
>>> y = x
>>> 
>>> x.resize((5, 2), refcheck=False)
>>> x[...] = np.c_[x.ravel()[:5], 1:6]
>>> 
>>> y
array([[ 1,  1],
       [ 5,  2],
       [ 3,  3],
       [ 4,  4],
       [10,  5]])

but you must be aware that switching off refchecking is dangerous:

>>> x = np.array([[ 1], [ 5], [ 3], [ 4], [10]])
>>> y = x[::2]
>>> 
>>> x.resize((5, 2), refcheck=False)
>>> 
>>> y
array([[29006928],
       [       0],
       [      48]])

As you can see y still references the now invalid data buffer of x before resizing.

答案 1 :(得分:0)

你可以用简单的列表理解来做到这一点:

[a+[i+1] for i,a in enumerate(array)]