如何将列表拆分为numpy数组?

时间:2019-05-23 09:16:25

标签: python-3.x numpy-ndarray

有关从列表填充np数组的基本问题:

m是一个形状为(4,486,9)的numpy数组。

d是一个列表,该列表的长度为23328,并且每个索引的项目数都不同。

我在维度1和2上遍历m,在维度1上遍历d。

我想以恒定的间隔从d的特定行中导入9个“列”到m中。这些列中的6列是连续的,它们在下面显示为索引“ some_index”。

我在下面所做的工作还可以,但是语法确实很繁琐,而且是错误的。必须有一种方法可以更有效地导出连续的列吗?

import numpy as np
m=np.empty(4,486,9)
d=[] #list filled in from files
#some_index is an integer incremented in the loops following some        conditions
#some_other_index is another integer incremented in the loops following some other conditions
For i in something:
    For j in another_thing:
        m[i][j]=[d[some_index][-7], d[some_index][-6], d[some_index][-5], d[some_index][-4], d[some_index][-3], d[some_index][-2], d[some_other_index][4], d[some_other_index][0], d[some_other_index][4]]

在没有太多想象力的情况下,我尝试了以下操作,因为np数组需要用逗号来区分项目,这些操作不起作用:

For i in something:
    For j in another_thing:
        m[i][j]=[d[some_index][-7:-1], d[some_other_index][4], d[some_other_index][0], d[some_other_index][4]]
ValueError: setting an array element with a sequence.

        m[i][j]=[np.asarray(d[some_index][-7:-1]), d[some_other_index][4], d[some_other_index][0], d[some_other_index][4]]
ValueError: setting an array element with a sequence.

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是您要寻找的吗?

您可以使用numpy数组一次选择多个元素。

我已自由创建一些数据,以确保我们做正确的事

import numpy as np
m=np.zeros((4,486,9))
d=[[2,1,2,3,1,12545,45,12], [12,56,34,23,23,6,7,4,173,47,32,3,4], [7,12,23,47,24,13,1,2], [145,45,23,45,56,565,23,2,2],
   [54,13,65,47,1,45,45,23], [125,46,5,23,2,24,23,5,7]] #list filled in from files
d = np.asarray([np.asarray(i) for i in d]) # this is where the solution lies
something = [2,3]
another_thing = [10,120,200]
some_index = 0
some_other_index = 5
select_elements = [-7,-6,-5,-4,-3,-2,4,0,4] # this is the order in which you are selecting the elements

for i in something:
    for j in another_thing:
        print('i:{}, j:{}'.format(i, j))
        m[i,j,:]=d[some_index][select_elements]

此外,我注意到您正在以这种方式m[i][j] = ...进行索引。您可以使用m[i,j,:] = ...

做同样的事情