python - 从元组列表中的项目构建二维 numpy 数组

标签 python numpy

给定一个 python 元组列表,例如:

test = [(1, 'string1', 47.9, -112.8, 6400.0),
        (2, 'string2', 29.7, -90.8, 11.0),
        (3, 'string3', 30.8, -99.1, 1644.0),
        (4, 'string4', 45.8, -110.9, 7500.0),
        (5, 'string5', 43.9, -69.8, 25.0)]

使用每个元组中的第 3 项和第 4 项构建 2D numpy 数组的最有效方法是什么?

期望的输出是:

array([[47.9, 29.7, 30.8, 45.8, 43.9],
       [-112.8, -90.8, -99.1, -110.9, -69.8]]) 

最佳答案

您可以使用选择第 3 项和第 4 项的列表推导式在 numpy 外部准备数据。然后你只需要转置结果数组:

np.array([x[2:4] for x in test]).T

关于python - 从元组列表中的项目构建二维 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54369583/

相关文章:

python - 如何使用 numpy 从源代码构建 pytorch

numpy - Scipy.optimize - 使用固定参数进行曲线拟合

python - 为什么使用 numpy.ndarray.astype 将 numpy.ndarray 转换为自定义数据类型会使我的数据相乘?

javascript - 如何将scrapyjs功能集成到Scrapy项目中

python - 为什么 dtype=object 的 numpy 数组产生的文件大小比 dtype=int 小得多?

python - Python 和 Matlab 中的克罗内克积

python - 如何不导入Python模块中导入的子模块?

Python Pandas 识别随时间的变化

Python简单socket聊天用户连接并输出消息

python - 如何读取夹在某个字符之间的数据(Python 3.3)