如何将 numpy 对象数组转换为 str/unicode 数组? [英] How to convert numpy object array into str/unicode array?
问题描述
更新:在 numpy 的最新版本(例如 v1.8.1)中,这不再是问题.这里提到的所有方法现在都可以正常工作.
原问题: 有时使用object dtype 来存储字符串数组很方便,特别是当需要修改大数组的内容而无需事先知道字符串的最大长度时,例如,
<预><代码>>>>将 numpy 导入为 np>>>a = np.array([u'abc', u'12345'], dtype=object)在某些时候,人们可能希望将 dtype 转换回 unicode 或 str.但是,简单的转换会截断长度为 4 或 1 的字符串(为什么?),例如,
<预><代码>>>>b = np.array(a, dtype=unicode)>>>乙数组([u'abc',u'1234'],dtype='<U4')>>>c = a.astype(unicode)>>>C数组([u'a', u'1'], dtype='<U1')当然,我们总是可以显式地遍历整个数组来确定最大长度,
<预><代码>>>>d = np.array(a, dtype='<U{0}'.format(np.max([len(x) for x in a])))数组([u'abc',u'12345'],dtype='<U5')然而,在我看来这有点尴尬.有没有更好的方法来做到这一点?
编辑添加:根据这个密切相关的问题,
<预><代码>>>>len(max(a, key=len))是另一种找出最长字符串长度的方法,这一步似乎是不可避免的...
我知道这是一个老问题,但如果有人遇到它并正在寻找答案,请尝试
c = a.astype('U')
你应该得到你期望的结果:
c = array([u'abc', u'12345'], dtype='<U5')
Update: In lastest version of numpy (e.g., v1.8.1), this is no longer a issue. All the methods mentioned here now work as excepted.
Original question: Using object dtype to store string array is convenient sometimes, especially when one needs to modify the content of a large array without prior knowledge about the maximum length of the strings, e.g.,
>>> import numpy as np
>>> a = np.array([u'abc', u'12345'], dtype=object)
At some point, one might want to convert the dtype back to unicode or str. However, simple conversion will truncate the string at length 4 or 1 (why?), e.g.,
>>> b = np.array(a, dtype=unicode)
>>> b
array([u'abc', u'1234'], dtype='<U4')
>>> c = a.astype(unicode)
>>> c
array([u'a', u'1'], dtype='<U1')
Of course, one can always iterate over the entire array explicitly to determine the max length,
>>> d = np.array(a, dtype='<U{0}'.format(np.max([len(x) for x in a])))
array([u'abc', u'12345'], dtype='<U5')
Yet, this is a little bit awkward in my opinion. Is there a better way to do this?
Edit to add: According to this closely related question,
>>> len(max(a, key=len))
is another way to find out the longest string length, and this step seems to be unavoidable...
I know this is an old question but in case anyone comes across it and is looking for an answer, try
c = a.astype('U')
and you should get the result you expect:
c = array([u'abc', u'12345'], dtype='<U5')
这篇关于如何将 numpy 对象数组转换为 str/unicode 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!