3

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?

3 Answers 3

11

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

Comments

1

You can use numpy.append:

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

np.append(a, 'z')
# array(['x', 'y', 'z'], 
#       dtype='<U1')

Comments

0

As alternative to append (since you can use it for several iterables; check for example: PEP3132) you can use the "unpacking" symbol to do it:

import numpy as np

a = np.array(['x','y'], dtype=object)
b = np.array([*a, "z"])
print(*a, "z")
print(b)

The result is this:

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

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.