[英]sum every element of first array with all the elements of second array
I have two arrays: 我有两个数组:
array1 = [1,2,3]
array2 = [10,20,30]
I want the next sum: 我想要下一笔钱:
array3 = [10+1,10+2,10+3,20+1,20+2,20+3,30+1,30+2,30+3]
How can I do that? 我怎样才能做到这一点? (I know that it can be done with two
for
loops but I want something more efficient if possible) (我知道可以用两个
for
循环来完成,但是如果可能的话我想要更有效的东西)
Note: those two arrays are contained in a dataframe (pandas) 注意:这两个数组包含在数据帧(pandas)中
I do not think pandas is necessary here 我不认为这里有大熊猫
[x+y for x in array2 for y in array1]
Out[293]: [11, 12, 13, 21, 22, 23, 31, 32, 33]
If they are in the dataframe 如果它们在数据框中
df=pd.DataFrame({'a':array1,'b':array2})
df
Out[296]:
a b
0 1 10
1 2 20
2 3 30
df.a.values+df.b.values[:,None]
Out[297]:
array([[11, 12, 13],
[21, 22, 23],
[31, 32, 33]], dtype=int64)
Update 更新
(df.a.values+df.b.values[:,None]).ravel()
Out[308]: array([11, 12, 13, 21, 22, 23, 31, 32, 33], dtype=int64)
I wanted to recommend using itertools.product here, https://docs.python.org/3/library/itertools.html included a lot of other recipes that allows you to code more clearly 我想建议在这里使用itertools.product, https: //docs.python.org/3/library/itertools.html包含了许多其他配方,可以让你更清晰地编码
from itertools import product
array1 = [1,2,3]
array2 = [10,20,30]
[x+y for x,y in product(array1,array2)]
# fp style
[*map(sum, product(array1,array2))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.