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'
A parenthesized number followed by a comma denotes a tuple with one element. The trailing comma distinguishes a one-element tuple from a parenthesized n . In a dimension entry, instructs NumPy to choose the length that will keep the total number of array elements the same.
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?
You can simply call tolist:
import numpy as np
a = np.array(['blue', 'red', 'green'])
b = a.tolist()
print(b)
['blue', 'red', 'green']
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])
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With