简体   繁体   English

如何生成二维 numpy 数组?

[英]How to generate 2d numpy array?

I'm trying to generate a 2d numpy array with the help of generators:我试图在生成器的帮助下生成一个 2d numpy 数组:

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.正如预期的那样,我得到了一个 np.array 的 np.array。 But I want not this, but ndarray, so I can get, for example, column in a way like this:但我想要的不是这个,而是 ndarray,所以我可以像这样获得列:

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.当然,可以创建所需大小的 npdarray 并用所需的值填充它,但我想要一种在一行代码中这样做的方法。

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])

To create a new array, it seems numpy.zeros is the way to go要创建一个新数组,似乎numpy.zeros是要走的路

import numpy as np
a = np.zeros(shape=(x, y))

You can also set a datatype to allocate it sensibly您还可以设置数据类型以合理分配它

>>> np.zeros(shape=(5,2), dtype=np.uint8)
array([[0, 0],
       [0, 0],
       [0, 0],
       [0, 0],
       [0, 0]], dtype=uint8)
>>> np.zeros(shape=(5,2), dtype="datetime64[ns]")
array([['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000'],
       ['1970-01-01T00:00:00.000000000', '1970-01-01T00:00:00.000000000']],
      dtype='datetime64[ns]')

See also也可以看看

Its very simple, do like this很简单,这样做

import numpy as np

arr=np.arange(50)
arr_2d=arr.reshape(10,5)    #Reshapes 1d array in to 2d, containing 10 rows and 5 coloumns.
print(arr_2d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM