1

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 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do that with simple list comprehension :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.