从简单列表中创建一个numpy数组的形状

时间:2015-09-06 11:05:01

标签: python arrays numpy

我有一个数字列表

mylist = [0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]

我在一个numpy数组中转换了mylist

import numpy as np
mylist_np = np.array(mylist)

array([ 0, 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29])

我希望将数组赋予形状:

array([[0, 1,2,3,4,5,6,7,8,9],
[10,11,12,13,14,15,16,17,18,19],
[20,21,22,23,24,25,26,27,28,29]])

1 个答案:

答案 0 :(得分:2)

Numpy不支持参差不齐的数组(至少,不会破坏某些基本方法的结果)

如果你的阵列是

array([ 0, 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
   18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29])

然后可以通过以下方式重塑:

np.reshape(mylist_np, (3,10))

但为什么要使用numpy?您可以使用以下内容设置数组:

my_list = [range(max(a,1),a+10) for a in range(0,30,10)]