[英]How to add numpy array variables by index without using loops
I have this problem where I would prefer not using loops because I am working with a big data as a solution:我有这个问题,我不想使用循环,因为我正在使用大数据作为解决方案:
This is what I am trying to do: (I know this works to [6 6 6], but I want to "join" it by index)这就是我想要做的:(我知道这适用于 [6 6 6],但我想通过索引“加入”它)
import numpy as np
np_1 = np.asarray([1,1,1])
np_2 = np.asarray([2,2,2])
np_3 = np.asarray([3,3,3])
np_4 = np_1 + np_2 + np_3
# np_4 should be [1,2,3,1,2,3,1,2,3]
Are there ways to do this?有没有办法做到这一点? or should I look for options outside of numpy?
还是我应该寻找 numpy 之外的选项?
You can try the following method:您可以尝试以下方法:
np.ravel(np.stack(np_1,np_2,np3),'F')
One way to do it is to stack the sequences depth-wise and flatten it:一种方法是深度堆叠序列并将其展平:
np.dstack([np_1, np_2, np_3]).flatten()
Try this:尝试这个:
np.array([np_1, np_2, np_3]).transpose().flatten()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.