Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a comma between the elements of a numpy array

Tags:

python

numpy

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'

like image 724
ulrich Avatar asked Aug 15 '15 16:08

ulrich


People also ask

Why does my NumPy array have commas?

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.


3 Answers

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?

like image 100
DeepSpace Avatar answered Oct 19 '22 23:10

DeepSpace


You can simply call tolist:

import numpy as np

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

b = a.tolist()
print(b)
['blue', 'red', 'green']
like image 21
Padraic Cunningham Avatar answered Oct 20 '22 01:10

Padraic Cunningham


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])
>>> 
like image 37
hebeha Avatar answered Oct 20 '22 00:10

hebeha