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
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.
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