Reputation: 29
What is the easiest way to expand and populate a python numpy array? Initially the numpy array is:
[[1,3], [1,2], [1,5]]
after expanding, the array should be:
[[1,3,9,27], [1,2,4,8], [1,5,25,125]]
the newly added column is the squared and cubed value of the 2nd column.
Thanks!
Upvotes: 1
Views: 76
Reputation: 221524
Slice the second column keeping the dimensions with a[:,[1]]
, perform the power operations leveraging broadcasting
with **[2,3]
, because we had kept the dimensions and then stack the output as new columns with np.c_
(one of many ways to stack).
Hence, the implementation -
np.c_[a,a[:,[1]]**[2,3]]
Sample output -
In [902]: np.c_[a,a[:,[1]]**[2,3]]
Out[902]:
array([[ 1, 3, 9, 27],
[ 1, 2, 4, 8],
[ 1, 5, 25, 125]])
Upvotes: 2
Reputation: 55469
You just need to skip over the 1 in each row, and then use broadcasting to form the desired cartesian product.
import numpy as np
a = np.array([[1,3], [1,2], [1,5]])
b = a[:, 1:] ** np.arange(4)
print(b)
output
[[ 1 3 9 27]
[ 1 2 4 8]
[ 1 5 25 125]]
Upvotes: 0