Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array of chars to string

I have a 2D numpy char array (from a NetCDF4 file) which actually represents a list of strings. I want to convert it into a list of strings.

I know I can use join() to concatenate the chars into a string, but I can only find a way to do this one string at a time:

data = np.array([['a','b'],['c','d']])
for row in data[:]:
    print ''.join(row)

But it's very slow. How can I return an array of strings in a single command? Thanks

like image 501
AdrianR Avatar asked Jun 11 '12 17:06

AdrianR


1 Answers

The list comprehension is the most "pythonic" way.

The most "numpythonic" way would be:

>>> data = np.array([['a','b'],['c','d']])
# a 2D view
>>> data.view('S2')
array([['ab'],
       ['cd']], 
      dtype='|S2')
# or maybe a 1D view ...fastest solution:
>>> data.view('S2').ravel()
array(['ab', 'cd'], 
      dtype='|S2')

No looping, no list comprehension, not even a copy. The buffer just sits there unchanged with a different "view" so this is the fastest solution available.

like image 116
Phil Cooper Avatar answered Oct 07 '22 16:10

Phil Cooper