Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append elements to a numpy array

Tags:

python

numpy

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.

like image 303
user3025898 Avatar asked Mar 09 '15 14:03

user3025898


1 Answers

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.

like image 132
user3590169 Avatar answered Oct 20 '22 23:10

user3590169