12

I have a numpy array which looks like

a = ['blue' 'red' 'green']

and I want it to become

b = ['blue', 'red', 'green']

I tried

b = a.split(' ')

but it returns an error: 'numpy.ndarray' object has no attribute 'split'

3

3 Answers 3

28

Simply turn it to a list:

a = numpy.array(['blue', 'red', 'green'])
print a
>> ['blue' 'red' 'green']
b = list(a)
print b
>> ['blue', 'red', 'green']

But why would you have a numpy array with strings?

Sign up to request clarification or add additional context in comments.

1 Comment

record arrays, recarrays, structured arrays... are a very common useage of numpy arrays. Numpy doesn't limit its dtype to one common type. There is extensive documentation in the Numpy and SciPy documentation websites. The only requirement is that each column/field is characterized by one dtype
8

You can simply call tolist:

import numpy as np

a = np.array(['blue', 'red', 'green'])

b = a.tolist()
print(b)
['blue', 'red', 'green']

Comments

4

I had a similar problem with a list without commas and with arbitrary number of spaces. E.g.:

[2650   20    5]
[2670    5]
[1357  963  355]

I solved it this way:

np.array(re.split("\s+", my_list.replace('[','').replace(']','')), dtype=int)

From the console:

>>> import numpy as np
>>> import re
>>> my_list = '[2650   20    5]'
>>> result = np.array(re.split("\s+", my_list.replace('[','').replace(']','')), dtype=int)
>>> result
array([2650,   20,    5])
>>> 

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.