Search code examples
pythonnumpygenerator

How to generate 2d numpy array?


I'm trying to generate a 2d numpy array with the help of generators:

x = [[f(a) for a in g(b)] for b in c]

And if I try to do something like this:

x = np.array([np.array([f(a) for a in g(b)]) for b in c])

I, as expected, get a np.array of np.array. But I want not this, but ndarray, so I can get, for example, column in a way like this:

y = x[:, 1]

So, I'm curious whether there is a way to generate it in such a way.

Of course it is possible with creating npdarray of required size and filling it with required values, but I want a way to do so in a line of code.


Solution

  • This works:

    a = [[1, 2, 3], [4, 5, 6]]
    nd_a = np.array(a)
    

    So this should work too:

    nd_a = np.array([[x for x in y] for y in a])