AdrianR
AdrianR

Reputation: 101

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

Upvotes: 10

Views: 13001

Answers (3)

user545424
user545424

Reputation: 16189

[row.tostring() for row in data]

Upvotes: 2

Phil Cooper
Phil Cooper

Reputation: 5877

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.

Upvotes: 14

Chris
Chris

Reputation: 46346

Try a list comprehension:

>> s = [''.join(row) for row in data]
>> s
['ab', 'cd']

which is just your for loop rewritten.

Upvotes: 5

Related Questions