字符串的numpy数组 [英] numpy array of chars to string

查看:212
本文介绍了字符串的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D numpy char数组(来自NetCDF4文件),它实际上表示一个字符串列表.我想将其转换为字符串列表.

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.

我知道我可以使用join()将字符连接成一个字符串,但是我只能找到一种方法一次处理一个字符串:

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

推荐答案

列表理解是最"pythonic"的方式.

The list comprehension is the most "pythonic" way.

最"numpythonic"的方式是:

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.

这篇关于字符串的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆