1

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!

2 Answers 2

2

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

you are the best!
0

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]]

Comments

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.