Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a NumPy array to a NumPy array

Tags:

python

numpy

I'm trying to populate a NumPy array of NumPy arrays. Every time I finish an iteration of a loop I create the array to be added. I would then like to append that array to the end of another array. For example:

first iteration
  np.append([], [1, 2]) => [[1, 2]]
next iteration
  np.append([[1, 2]], [3, 4]) => [[1, 2], [3, 4]]
next iteration
  np.append([[1, 2], [3, 4]], [5, 6]) => [[1, 2], [3, 4], [5, 6]]
etc.

I've tried using np.append but this returns a one dimensional array, i.e.

[1, 2, 3, 4, 5, 6]
like image 788
UBears Avatar asked Mar 02 '17 01:03

UBears


3 Answers

Nest the arrays so that they have more than one axis, and then specify the axis when using append.

import numpy as np
a = np.array([[1, 2]]) # note the braces
b = np.array([[3, 4]])
c = np.array([[5, 6]])

d = np.append(a, b, axis=0)
print(d)
# [[1 2]
#  [3 4]]

e = np.append(d, c, axis=0)
print(e)
# [[1 2]
#  [3 4]
#  [5 6]]

Alternately, if you stick with lists, use numpy.vstack:

import numpy as np
a = [1, 2]
b = [3, 4]
c = [5, 6]

d = np.vstack([a, b])
print(d)
# [[1 2]
#  [3 4]]

e = np.vstack([d, c])
print(e)
# [[1 2]
#  [3 4]
#  [5 6]]
like image 185
pml Avatar answered Sep 23 '22 12:09

pml


I found it handy to use this code with numpy. For example:

loss = None
new_coming_loss = [0, 1, 0, 0, 1]
loss = np.concatenate((loss, [new_coming_loss]), axis=0) if loss is not None else [new_coming_loss]

Practical Use:

self.epoch_losses = None
self.epoch_losses = np.concatenate((self.epoch_losses, [loss.flatten()]), axis=0) if self.epoch_losses is not None else [loss.flatten()]

Copy and paste solution:

def append(list, element):
    return np.concatenate((list, [element]), axis=0) if list is not None else [element]

WARNING: the dimension of list and element should be the same except the first dimension, otherwise you will get:

ValueError: all the input array dimensions except for the concatenation axis must match exactly
like image 23
Koke Cacao Avatar answered Sep 23 '22 12:09

Koke Cacao


Disclaimer: appending arrays should be the exception, because it is inefficient.

That said, you can achieve your aim by specifying an axis

a = np.empty((0, 2))
a = np.append(a, [[3,6]], axis=0)
a = np.append(a, [[1,4]], axis=0)
like image 21
Paul Panzer Avatar answered Sep 21 '22 12:09

Paul Panzer