简体   繁体   English

将列表转换为 Numpy 二维数组

[英]Convert List into Numpy 2D Array

How to convert a list into a numpy 2D ndarray.如何将列表转换为 numpy 2D ndarray。 For example:例如:

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

Expected result:预期结果:

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

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

Convert it to array and reshape:将其转换为数组并重塑:

x = np.array(x).reshape(-1,1)

reshape adds the column structure. reshape 添加列结构。 The -1 in reshape takes care of the correct number of rows it requires to reshape. reshape中的 -1 负责调整所需的正确行数。

output: output:

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

If you need your calculations more effective, use numpy arrays instead of list comprehensions.如果您需要更有效的计算,请使用 numpy arrays 而不是列表推导。 This is an alternative way using array broadcasting这是使用数组广播的另一种方式

x = [20, 30, 40, 50, 60]
x = np.array(x) #convert your list to numpy array
result = x[:, None] #use numpy broadcasting

if you still need a list type at the end, you can convert your result efficiently using result.tolist()如果最后仍然需要列表类型,则可以使用result.tolist()有效地转换结果

You may use a list comprehension and then convert it to numpy array:您可以使用列表推导,然后将其转换为 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.

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