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

How to split list into numpy array?

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

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

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

我在维度 1 和维度 2 上迭代 m,在维度 1 上迭代 d。

我想以恒定间隔从 d 的特定行导入 9 "columns" 到 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.

感谢您的帮助。

这是您要找的吗?

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

我冒昧地创建了一些数据,以确保我们做的是正确的

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,:] = ...

做同样的事情