python-3.x - 如何将列表拆分为numpy数组?
问题描述
关于从列表中填充 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.
谢谢你的帮助。
解决方案
这是你想要的?
您可以使用 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,:] = ...
推荐阅读
- json - 使用 POST 方法时 Angular 6 中的 TypeError 循环对象值
- python - 销售速度定义为 sales/running_days
- angular - 如何通过 Angular 传递 URL?
- r - 无法在 RStudio 中创建正确的公式
- python - How to use yield instead of print with scrapy selector and selenium?
- regex - 从字符串中提取逗号分隔的数字
- reactjs - 无法在反应导航中从内部堆栈导航到外部堆栈
- javascript - Django:显示字典中的图像
- youtube-api - 提高 YouTube API 的配额限制
- python - 当模板中存在另一个表单时,如何知道提交按钮是否使用 get 方法单击了表单?