0

This Python 3.8 code snippet:

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
a = np.concatenate((a, b), axis=0)
print(a) 

produces:

[[1 2]
 [3 4]
 [5 6]]

as expected. How do I define an empty array e, such that this code produces the same result:

# define en empty array e here
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
e = np.concatenate((e, a), axis=0)
e = np.concatenate((e, b), axis=0)
print(e) 

The use case here is an algorithm, which starts with an empty array and concatenates additional arrays to it in a loop.

8
  • 1
    Why not e = np.concatenate((a, b), axis=0)? Commented Nov 12, 2021 at 11:14
  • 1
    Does this answer your question? Concatenating empty array in Numpy Commented Nov 12, 2021 at 11:14
  • @DaniMesejo I have to start with an empty array for brevity and elegance. Commented Nov 12, 2021 at 11:17
  • 2
    Elegance is in the eye of the beholder... and the answer posted is for sure not more breve (in terms of LOC) that the one in the question. Commented Nov 12, 2021 at 11:19
  • 1
    @DaniMesejo Obviously not an elegance of the snippet I posted. Brevity of an algorithm, which assumes an empty array at the beginning. Commented Nov 12, 2021 at 11:27

1 Answer 1

1

Found it:

e = np.empty((0, 2))
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
e = np.concatenate((e, a), axis=0)
e = np.concatenate((e, b), axis=0)
print(e) 
Sign up to request clarification or add additional context in comments.

4 Comments

better yet f = np.concatenate((e,a,b), axis=0). One concatenate on the full list is better than repeated ones. Less copying.
@hpaulj Yes, but that wasn't the question.
Sorry, I mistook you for a beginner who didn't realize that list append is more efficient than repeated np.concatenate. List append works in-place, and just adds a reference. concatenate makes a new array each time, with all the copying that entails. So yes, if you want to concatenate a "empty" array it needs to have the same number of dimensions as the others, here (0,2), (2,2) , (1,2). Calling np.empty((0,2)) "empty" is a bit of a misnomer. It shouldn't be confused with the list [].
Watch the dtype with this code. e is a float, a is int. Conditional code that sets e=a on the first iteration may be safer, and a bit faster (one less concatenate), even it it isn't as pretty.

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.