blaziken105
blaziken105

Reputation: 501

Appending a new row to a numpy array

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]...]

Upvotes: 1

Views: 18452

Answers (2)

hpaulj
hpaulj

Reputation: 231325

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.

Upvotes: 4

MSeifert
MSeifert

Reputation: 152587

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.

Upvotes: 1

Related Questions