2

I have a list 'Z' with:

import numpy as np
z[0] = np.random.normal( 0, 1, ( 500, 20 ) )
z[1] = np.random.normal( 0, 1, ( 500, 30 ) )

There are about 100 arrays in the list. I am using only size 2 list for illustration. The stored arrays are all of dimension 0 of 500

I want to achieve:

C = np.concatenate( ( z[0] , z[1] ),1)

I tried:

z1 = [ np.concatenate( z[ii], 1 ) for ii in range(0,len(z)) ] 

but it still returns the original list and doesn't concatenate the stored arrays

2 Answers 2

6

Concatenation for multidimensional arrays is somewhat ill-defined without specifying an axis along which to concatenate. I assume you want to stack your arrays horizontally because the number of rows is the same for both. The simplest call is

stacked = np.hstack(Z)

which will concatenate along axis 1. You can find documentation here.

More generally, you can also use

stacked = np.concatenate(Z, axis=1)

which works for higher-dimensional arrays, too. The corresponding documentation is here.

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

Comments

1

I was confused by the numpy stuff, but now I see what you were asking. You just have your list comprehension inside out.

Rather than

z1 = [ np.concatenate( z[ii], 1 ) for ii in range(0,len(z)) ] 

You want

z1 = np.concatenate((z[ii] for ii in range(0, len(z)), 1)

Note that I changed it to a generator expresssion, as you don't really care about the intermediate list.

2 Comments

You can also just pass z rather than wrapping it in an iterator.
@TillHoffmann Nice - I am terribly unfamiliar with Numpy, only used it a couple of times in college.

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.