0

Problem:

  • The function f returns the numpy ndarrays np_array_1, np_array_2. Both arrays have the same length, but this length may be different for each call.
  • I want to call f several times and keep only the two arrays concatenated from the different calls.

Question: Is there a way to do it without using temporal variables? Using temporal variables:

def f(i):
   ...
   return np_array_1, np_array_2

np_array_1, np_array_2 = f(0)
for i in range(1, 5):
   np_array_1_t, np_array_2_t = f(i)
   np_array_1 = np.concatenate(np_array_1, np_array_1_t)
   np_array_2 = np.concatenate(np_array_2, np_array_2_t)
del np_array_1_t, np_array_2_t
2
  • concatenate works with a list of many arrays, not just 2. Commented Jun 29, 2021 at 11:40
  • @hpaulj What do you mean with this? Why would I use more than two arrays? Commented Jun 29, 2021 at 13:15

2 Answers 2

1

This may make the list operations of the other answer more understandable

alist1 = []; alist2 = []
np_array_1, np_array_2 = f(0)
for i in range(0, 5):
   a1, a2 = f(i)
   alist1.append(a1); alist2.append(a2)
np_array_1 = np.concatenate(alist1)
np_array_2 = np.concatenate(alist2)

concatenate and array (and variations) all take a list of arrays as input. It's better to collect the arrays in one list, and do just on concatenate. List append is more efficient and suitable for iterative application.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand your question correctly the following works:

a1s, a2s = zip(*(f(i) for i in range(5)))
a1 = np.concatenate(a1s)
a2 = np.concatenate(a2s)

Or even simpler if all arrays have the same size:

a1, a2 = np.array([f(i) for i in range(5)]).squeeze().T

1 Comment

In general the arrays in my problem do not have the same size. Your first approach still uses temporal variables, but it is more concise than the method I thought. However, I do not completely understand it. So (f(i) for i in range(5)) is like a tuple of 5 tuples of 2 arrays? I am a bit lost with the asterisk and the zip...

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.