Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Add an Item to an Array

I have an ndarray that looks like this:

In  [1]: a
Out [1]: array(['x','y'], dtype=object)

Now I wanted to append a "z" to the end of it:

In  [2]: print([a,'z'])
[array(['x','y'],dtype=object), 'z']

Instead, what I want is:

['x','y','z']

Any idea?

like image 206
Jingwei Yu Avatar asked May 07 '26 20:05

Jingwei Yu


2 Answers

You can do it using numpy.append:

import numpy as np

a = np.array(['x','y'])

b = np.append(a,['z'])

In [8]:b
Out[8]: array(['x', 'y', 'z'], dtype='<U1')
like image 59
Wenlong Liu Avatar answered May 10 '26 10:05

Wenlong Liu


You can use numpy.append:

import numpy as np
a = np.array(['x', 'y'])

np.append(a, 'z')
# array(['x', 'y', 'z'], 
#       dtype='<U1')
like image 30
Psidom Avatar answered May 10 '26 11:05

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!