Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

python - Concatenate arrays inside a tuple in simpler way

I have a tuple X whose element is 2-D numpy arrays that have same 1st dimension and different 2nd dimension. I want to concatenate those arrays to make 1 big array. For example:

X = (np.array of shape[10,3], np.array of shape[10,5], np.array of shape[10,7]). I want to make a final array Y that has a shape of [10,15] which is the concatenation of all elements in tuple X.

I did something like this. It works, but I'm asking if there is any shorter/simpler way to do this? Thanks!

def concat_arrays(data: tuple) -> np.ndarray:
    final_array = data[0]
    for i in range(len(data)):
        if i > 0:
            final_array = np.hstack((final_array,data[i]))
    return final_array 
question from:https://stackoverflow.com/questions/66061156/concatenate-arrays-inside-a-tuple-in-simpler-way

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is this simple:

def concat_arrays(data: tuple) -> np.ndarray:
    return np.hstack(data)

There is no need to iterate through and stack one at a time - that's why you are asked to pass a tuple instead of two separate arguments. (That isn't a real restriction in Python anyway - because *args exists - but still.)

But of course, there is no point to writing this, as we could simply use np.hstack directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...