Let’s say I have a NumPy array, a
:
a = np.array([
[1, 2, 3],
[2, 3, 4]
])
And I would like to add a column of ze
np.insert also serves the purpose.
matA = np.array([[1,2,3],
[2,3,4]])
idx = 3
new_col = np.array([0, 0])
np.insert(matA, idx, new_col, axis=1)
array([[1, 2, 3, 0],
[2, 3, 4, 0]])
It inserts values, here new_col
, before a given index, here idx
along one axis. In other words, the newly inserted values will occupy the idx
column and move what were originally there at and after idx
backward.
Assuming M
is a (100,3) ndarray and y
is a (100,) ndarray append
can be used as follows:
M=numpy.append(M,y[:,None],1)
The trick is to use
y[:, None]
This converts y
to a (100, 1) 2D array.
M.shape
now gives
(100, 4)
I was also interested in this question and compared the speed of
numpy.c_[a, a]
numpy.stack([a, a]).T
numpy.vstack([a, a]).T
numpy.ascontiguousarray(numpy.stack([a, a]).T)
numpy.ascontiguousarray(numpy.vstack([a, a]).T)
numpy.column_stack([a, a])
numpy.concatenate([a[:,None], a[:,None]], axis=1)
numpy.concatenate([a[None], a[None]], axis=0).T
which all do the same thing for any input vector a
. Timings for growing a
:
Note that all non-contiguous variants (in particular stack
/vstack
) are eventually faster than all contiguous variants. column_stack
(for its clarity and speed) appears to be a good option if you require contiguity.
Code to reproduce the plot:
import numpy
import perfplot
perfplot.save(
"out.png",
setup=lambda n: numpy.random.rand(n),
kernels=[
lambda a: numpy.c_[a, a],
lambda a: numpy.ascontiguousarray(numpy.stack([a, a]).T),
lambda a: numpy.ascontiguousarray(numpy.vstack([a, a]).T),
lambda a: numpy.column_stack([a, a]),
lambda a: numpy.concatenate([a[:, None], a[:, None]], axis=1),
lambda a: numpy.ascontiguousarray(
numpy.concatenate([a[None], a[None]], axis=0).T
),
lambda a: numpy.stack([a, a]).T,
lambda a: numpy.vstack([a, a]).T,
lambda a: numpy.concatenate([a[None], a[None]], axis=0).T,
],
labels=[
"c_",
"ascont(stack)",
"ascont(vstack)",
"column_stack",
"concat",
"ascont(concat)",
"stack (non-cont)",
"vstack (non-cont)",
"concat (non-cont)",
],
n_range=[2 ** k for k in range(20)],
xlabel="len(a)",
logx=True,
logy=True,
)
I liked this:
new_column = np.zeros((len(a), 1))
b = np.block([a, new_column])
Numpy's np.append
method takes three parameters, the first two are 2D numpy arrays and the 3rd is an axis parameter instructing along which axis to append:
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
print("Original x:")
print(x)
y = np.array([[1], [1]])
print("Original y:")
print(y)
print("x appended to y on axis of 1:")
print(np.append(x, y, axis=1))
Prints:
Original x:
[[1 2 3]
[4 5 6]]
Original y:
[[1]
[1]]
x appended to y on axis of 1:
[[1 2 3 1]
[4 5 6 1]]
A bit late to the party, but nobody posted this answer yet, so for the sake of completeness: you can do this with list comprehensions, on a plain Python array:
source = a.tolist()
result = [row + [0] for row in source]
b = np.array(result)