0

I am trying to concatenate a set of numpy arrays loaded from disk. All arrays have varying number of columns.

This is my code

import numpy as np

FILE_LIST = ["matrix a", "matrix b"]

result=np.array([[0,0],[0,0]]) # I need to avoid this zero matrix
for fileName in FILE_LIST:
    matrix = matrix= np.genfromtxt(fileName, delimiter=" ")    
    result = np.concatenate((result, matrix),axis=1) 

print result

Here I have initialised result to an array with zeroes as I cannot concatenate to an empty array. I need to avoid this zero array appended at the beginning of the result. How to achieve this?

2 Answers 2

2

I would recommend to first load all the data in an array and then apply numpys hstack in order to horizontally stack the arrays

result = np.hstack([np.genfromtxt(fileName,delimiter=" ") for fileName in FILE_LIST])
Sign up to request clarification or add additional context in comments.

Comments

0

It's not obvious why you need to avoid this. But you could do:

result=None
for fileName in FILE_LIST:
    matrix= np.genfromtxt(fileName, delimiter=" ")
    if result is None:
        result = matrix
    else:
        result = np.concatenate((result, matrix),axis=1) 

Generally we try to avoid repeated concatenation (or append) to arrays, prefering instead to append to lists. But in this case genfromtxt is a big enough operation that it doesn't matter much how you combine the arrays.

With a list, the loop would be:

result=[]
for fileName in FILE_LIST:
    result.append(np.genfromtxt(fileName, delimiter=" "))    
result = np.concatenate(result,axis=1) 

A list comprehension is essentially the same thing.

Comments

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.