从元组列表中的项目构建2D numpy数组

时间:2019-01-25 16:50:45

标签: 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个项构建二维numpy数组的最有效方法是什么?

所需的输出是:

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

5 个答案:

答案 0 :(得分:3)

您可以使用列表解析来选择numpy之外的数据,该列表选择第3和第4项。然后,您只需要转置结果数组即可:

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

答案 1 :(得分:2)

zip列表,slice使用itertools.islice

from itertools import islice

np.array(list(islice(zip(*test), 2, 4)))
# array([[  47.9,   29.7,   30.8,   45.8,   43.9],
#        [-112.8,  -90.8,  -99.1, -110.9,  -69.8]])

答案 2 :(得分:1)

您可以将元组列表直接转换为数组,然后使用切片和转置来获得所需的输出:

import numpy as np

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)]

arr = np.array(test, dtype=object)
result = arr[:, 2:4].T.astype(np.float32)
print(result)

输出

[[  47.9   29.7   30.8   45.8   43.9]
 [-112.8  -90.8  -99.1 -110.9  -69.8]]

请注意,在完成arr = np.array(test)之后,所有操作都会在numpy级别完成。

答案 3 :(得分:1)

第一个列表是:

the_first = [item[2] for item in test]

第二个是:

 second = [item[3] for item in test]

结果是:

 result = np.array([the_first, second])

答案 4 :(得分:0)

您可以尝试以下方法:

import numpy as np

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)]

result = np.array([(item[3], item[4]) for item in test]).T
print(result)

# array([[-112.8,  -90.8,  -99.1, -110.9,  -69.8],
#       [6400. ,   11. , 1644. , 7500. ,   25. ]])