[英]Convert List into Numpy 2D Array
如何将列表转换为 numpy 2D ndarray。 例如:
lst = [20, 30, 40, 50, 60]
预期结果:
>> print(arr)
>> array([[20],
[30],
[40],
[50],
[60]])
>> print(arr.shape)
>> (5, 1)
将其转换为数组并重塑:
x = np.array(x).reshape(-1,1)
reshape 添加列结构。 reshape
中的 -1 负责调整所需的正确行数。
output:
[[20]
[30]
[40]
[50]
[60]]
如果您需要更有效的计算,请使用 numpy arrays 而不是列表推导。 这是使用数组广播的另一种方式
x = [20, 30, 40, 50, 60]
x = np.array(x) #convert your list to numpy array
result = x[:, None] #use numpy broadcasting
如果最后仍然需要列表类型,则可以使用result.tolist()
有效地转换结果
您可以使用列表推导,然后将其转换为 numpy 数组:
import numpy as np
x = [20, 30, 40, 50, 60]
x_nested = [[item] for item in x]
x_numpy = np.array(x_nested)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.