Python 将列表转换为二维 numpy 数组

标签 python list numpy

我有一些列表想转换成二维 numpy 数组。

list1 = [ 2, 7 , 8 , 5]
list2 = [18 ,29, 44,33]
list3 = [2.3, 4.6, 8.9, 7.7]

我想要的numpy数组是:

[[  2.   18.    2.3]
 [  7.   29.    4.6]
 [  8.   44.    8.9]
 [  5.   33.    7.7]]

我可以通过将列表中的各个项目直接输入到 numpy 数组表达式中作为 np.array(([2,18,2.3], [7,29, 4.6], [8,44 ,8.9], [5,33,7.7]), dtype=float).

但我希望能够将列表转换为所需的 numpy 数组。

最佳答案

一种方法是创建您的 numpy 数组,然后使用转置函数将其转换为您想要的输出:

import numpy as np

list1 = [ 2, 7 , 8 , 5]
list2 = [18 ,29, 44,33]
list3 = [2.3, 4.6, 8.9, 7.7]

arr = np.array([list1, list2, list3])
arr = arr.T
print(arr)

输出

[[  2.   18.    2.3]
 [  7.   29.    4.6]
 [  8.   44.    8.9]
 [  5.   33.    7.7]]

关于Python 将列表转换为二维 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35976770/

相关文章:

python - 如何使用 Python 在 ElasticSearch 中创建嵌套索引?

numpy - 使用 numpy 计算二进制掩码 IOU 的最快方法

python - 如何使用python计算Delta F/F?

python - 在 numpy 中计算累积乘积或总和时提前中断

python - 将多维数组转换为python中的元组

python - 如何获得由 zope.transaction 管理的 SQLAlchemy session ,它具有与 http 请求相同的范围但不会在提交时自动关闭?

python - 为什么在 Python 中将集合传递给 set.discard 时不会抛出错误?

c# - 删除列表中包含另一个名称的名称

linux - 如何通过将 ids 列表与 LINUX 中的另一个数据文件进行比较来给予 ids 列表相同的排名?

python - 优化Python : Large arrays,内存问题