Sum rows of 2D array with elements of 1D array
Question:
I have two ndarrays:
a = [[1, 2], [100, 200]]
and
b = [10, 20]
Is it possible to get such ndarray using numpy:
[[1 + 10, 2 + 10], [100 + 20, 200 + 20]]
Answers:
You just need to transpose the first array, perform the addition, then transpose back:
import numpy as np
a = np.array([[1, 2], [100, 200]])
b = np.array([10, 20])
x = a.T + b
print(x)
# [[ 11 120]
# [ 12 220]]
print(x.T)
# [[ 11 12]
# [120 220]]
Note that transposing an array is "free" so doing it several times is not a worry.
Edit: just for completeness, I have added a benchmarking test to compare all the approaches and they all seem to take the same time.
transposition: 0.180 ms
reshaping: 0.179 ms
newaxis: 0.181 ms
from contextlib import contextmanager
import numpy as np
from time import perf_counter
N = 10_000_000
@contextmanager
def time_this(message=""):
t0 = perf_counter()
yield
dt = perf_counter() - t0
print(f"{message}: {dt:.3f} ms")
a = np.random.random((N, 2))
b = np.random.random(N,)
with time_this("transposition"):
(a.T + b).T
with time_this("reshaping"):
a + b.reshape(-1, 1)
with time_this("newaxis"):
a + b[:,None]
Yes, this is possible using reshape.
import numpy as np
a = np.array([[1, 2], [100, 200]])
b = np.array([10, 20])
result = a + b.reshape(-1, 1) # is a column
Another possible solution, which is based on numpy broadcasting
:
a + b[:,None]
EXPLANATION
b[:,None]
is
array([[10],
[20]])
So by summing the two arrays, the array
array([[10],
[20]])
will be broadcasted and summed to each column of a
, producing the wanted result.
Output:
array([[ 11, 12],
[120, 220]])
I have two ndarrays:
a = [[1, 2], [100, 200]]
and
b = [10, 20]
Is it possible to get such ndarray using numpy:
[[1 + 10, 2 + 10], [100 + 20, 200 + 20]]
You just need to transpose the first array, perform the addition, then transpose back:
import numpy as np
a = np.array([[1, 2], [100, 200]])
b = np.array([10, 20])
x = a.T + b
print(x)
# [[ 11 120]
# [ 12 220]]
print(x.T)
# [[ 11 12]
# [120 220]]
Note that transposing an array is "free" so doing it several times is not a worry.
Edit: just for completeness, I have added a benchmarking test to compare all the approaches and they all seem to take the same time.
transposition: 0.180 ms
reshaping: 0.179 ms
newaxis: 0.181 ms
from contextlib import contextmanager
import numpy as np
from time import perf_counter
N = 10_000_000
@contextmanager
def time_this(message=""):
t0 = perf_counter()
yield
dt = perf_counter() - t0
print(f"{message}: {dt:.3f} ms")
a = np.random.random((N, 2))
b = np.random.random(N,)
with time_this("transposition"):
(a.T + b).T
with time_this("reshaping"):
a + b.reshape(-1, 1)
with time_this("newaxis"):
a + b[:,None]
Yes, this is possible using reshape.
import numpy as np
a = np.array([[1, 2], [100, 200]])
b = np.array([10, 20])
result = a + b.reshape(-1, 1) # is a column
Another possible solution, which is based on numpy broadcasting
:
a + b[:,None]
EXPLANATION
b[:,None]
is
array([[10],
[20]])
So by summing the two arrays, the array
array([[10],
[20]])
will be broadcasted and summed to each column of a
, producing the wanted result.
Output:
array([[ 11, 12],
[120, 220]])