Python 将列表转换为Numpy 2D数组

Python 将列表转换为Numpy 2D数组,python,arrays,numpy,Python,Arrays,Numpy,如何将列表转换为numpy 2D数据数组。例如: lst = [20, 30, 40, 50, 60] 预期结果: >> print(arr) >> array([[20], [30], [40], [50], [60]]) >> print(arr.shape) >> (5, 1) 您可以使用列表理解,然后将其转换为numpy数组: import numpy as np x = [2

如何将列表转换为numpy 2D数据数组。例如:

lst = [20, 30, 40, 50, 60]
预期结果:

>> print(arr)
>> array([[20],
       [30],
       [40],
       [50],
       [60]])

>> print(arr.shape)
>> (5, 1)

您可以使用列表理解,然后将其转换为numpy数组:

import numpy as np

x = [20, 30, 40, 50, 60]

x_nested = [[item] for item in x]

x_numpy = np.array(x_nested)


将其转换为阵列并重塑形状:

x = np.array(x).reshape(-1,1)
“重塑”将添加柱结构。
整形
中的-1负责整形所需的正确行数

输出:

[[20]
 [30]
 [40]
 [50]
 [60]]

如果您需要更有效的计算,请使用numpy数组而不是列表理解。这是使用


如果最后仍然需要列表类型,可以使用
result.tolist()

[[i]for i in x]
np.重塑([20,30,40,50,60],(-1,1))
?@Yoshi感谢您的建议,但这似乎对我没有太大帮助:(我只是误读了这个问题。@Sushanth答案是我认为你在寻找的:)这是一种效率低得多的技术。在处理数字数据时,尽可能快地将其输入numpy,然后对其进行操作。这不是广播,只是索引。
None
np.newaxis
的别名
x = [20, 30, 40, 50, 60]
x = np.array(x) #convert your list to numpy array
result = x[:, None] #use numpy broadcasting