15

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.

10
  • 3
    That looks more iteratively than recursively to me... also... have you looked at just using np.loadtxt to load data from files? Commented Mar 9, 2015 at 14:06
  • 1
    For what it's worth, none of your question has anything to do with recursion. You're just using looping, which is different from recursion. Beyond that, there's a lot of goofiness in your second example. You're trying to put strings of potentially arbitrary length into a Numpy array. Commented Mar 9, 2015 at 14:07
  • the variable "matrix" means that the file only contains numbers Commented Mar 9, 2015 at 14:13
  • A file containing only numbers can be loaded with np.loadtxt or np.genfromtxt. Appending to a NumPy array is slow. Avoid doing this if you can. Commented Mar 9, 2015 at 14:14
  • This is only an example, I know how to load files to numpy arrays and I know that it is better, the question is how to append values to numpy arrays in cases where I have to iterate as in a for loop. Commented Mar 9, 2015 at 14:18

1 Answer 1

23

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.

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

5 Comments

Please see the sample code provided, running your code returns an empty array []
Are you sure your input file is begin read correctly / has appropriate data? for i in range(5): np.append(A, i) Gives: array([ 0.]) array([ 1.]) array([ 2.]) array([ 3.]) array([ 4.]) So I believe this works.
this is the program I am running import numpy as np A = np.array([]) for i in range(5): np.append(A, i) print A it returns []
Thanks it is working now. Is there a way to save i as either a column or a as a row in your program?
@user3025898 Use the axis keyword argument for numpy.append. It will require getting the axes aligned with a transpose, i.e. A = numpy.append(A, row.T, axis=1)

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.