1

I am trying to append a new row to an existing numpy array in a loop. I have tried the methods involving append, concatenate and also vstack none of them end up giving me the result I want.

I have tried the following:

for _ in col_change:
if (item + 2 < len(col_change)):
    arr=[col_change[item], col_change[item + 1], col_change[item + 2]]
    array=np.concatenate((array,arr),axis=0)
    item+=1

I have also tried it in the most basic format and it still gives me an empty array.

array=np.array([])
newrow = [1, 2, 3]
newrow1 = [4, 5, 6]
np.concatenate((array,newrow), axis=0)
np.concatenate((array,newrow1), axis=0)
print(array)

I want the output to be [[1,2,3][4,5,6]...]

4
  • 1
    array = np.concatenate((array,newrow), axis=0) and array = np.concatenate((array,newrow1), axis=0). It doesn't work by reference. You need to have array = before the operations. Commented Jan 8, 2017 at 14:00
  • 1
    Already answered here : [1]: stackoverflow.com/questions/3881453/numpy-add-row-to-array Commented Jan 8, 2017 at 14:06
  • I tried that too but it ends up adding to the end of the row like this [ 1. 2. 3. 4. 5. 6.] Commented Jan 8, 2017 at 14:08
  • Just try array = np.vstack([np.concatenate([array, newrow]), newrow1]) then. All those options are available in the thread posted by Gyanshu. Commented Jan 8, 2017 at 14:24

2 Answers 2

4

The correct way to build an array incrementally is to not start with an array:

alist = []
alist.append([1, 2, 3])
alist.append([4, 5, 6])
arr = np.array(alist)

This is essentially the same as

arr = np.array([ [1,2,3], [4,5,6] ])

the most common way of making a small (or large) sample array.

Even if you have good reason to use some version of concatenate (hstack, vstack, etc), it is better to collect the components in a list, and perform the concatante once.

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

Comments

1

If you want [[1,2,3],[4,5,6]] I could present you an alternative without append: np.arange and then reshape it:

>>> import numpy as np

>>> np.arange(1,7).reshape(2, 3)
array([[1, 2, 3],
       [4, 5, 6]])

Or create a big array and fill it manually (or in a loop):

>>> array = np.empty((2, 3), int)
>>> array[0] = [1,2,3]
>>> array[1] = [4,5,6]
>>> array
array([[1, 2, 3],
       [4, 5, 6]])

A note on your examples:

In the second one you forgot to save the result, make it array = np.concatenate((array,newrow1), axis=0) and it works (not exactly like you want it but the array is not empty anymore). The first example seems badly indented and without know the variables and/or the problem there it's hard to debug.

1 Comment

I concatenated the array and then reshaped it, works fine now.

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.