4

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)

Note: those two arrays are contained in a dataframe (pandas)

1
  • 1
    Are they columns in a Pandas DataFrame? Because if so you should actually just put your DataFrame in your question instead of Python lists. Commented May 18, 2018 at 1:07

2 Answers 2

6

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)
Sign up to request clarification or add additional context in comments.

1 Comment

thats nice, but you second solution is an array of array and I want just one array, what can I do?
0

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

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))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.