简体   繁体   中英

Adding elements to numpy array

Using NumPy:

X= numpy.zeros(shape=[1, 4], dtype=np.int)

How can I add a list, such as [1,2,3,4] ? I tried numpy.add(X,[1,2,3,4]) and np.hstack((1,2,3,4)) but none of them work!

I know how to use that in standard Python list using append method but I want to use numpy for performance.

Numpy arrays don't change shape after they are created. So after invoking method zeros((1,4), ...) , you already have a 1x4 matrix full of zeroes. To set its elements to values other than zeroes, you need to use the assignment operator:

X[0] = [1, 2, 3, 4]  # does what you are trying to achieve in your question
X[0, :] = [1, 2, 3, 4]  # equivalent to the above
X[:] = [1, 2, 3, 4]  # same
X[0, 1] = 2  # set the individual element at [0, 1] to 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM