user3025898
user3025898

Reputation: 571

How to append elements to a numpy array

I want to do the equivalent to adding elements in a python list recursively in Numpy, As in the following code

matrix = open('workfile', 'w')
A = []
for row in matrix:
    A.append(row)

print A

I have tried the following:

matrix = open('workfile', 'w')
A = np.array([])
for row in matrix:
    A = numpy.append(row)

print A

It does not return the desired output, as in the list.

Edit this is the sample code:

mat = scipy.io.loadmat('file.mat')
var1 = mat['data1']
A = np.array([])
for row in var1:
    np.append(A, row)

print A

This is just the simplest case of what I want to do, but there is more data processing in the loop, I am putting it this way so the example is clear.

Upvotes: 15

Views: 70966

Answers (1)

user3590169
user3590169

Reputation: 396

You need to pass the array, A, to Numpy.

matrix = open('workfile', 'w')
A = np.array([])
for row in matrix:
    A = numpy.append(A, row)

print A

However, loading from the files directly is probably a nicer solution.

Upvotes: 23

Related Questions