我有一个空的unicode数组:
a = np.array([], dtype=np.str_)
我想对其进行编码:
b = np.char.encode(a, encoding='utf8')
为什么结果是dtype=float64
的空数组?
# array([], dtype=float64)
如果数组不为空,则生成的数组是一个正确编码的数组,具有dtype=|S[n]
:
a = np.array(['ss', 'ff☆'], dtype=np.str_)
b = np.char.encode(a, encoding='utf8')
# array([b'ss', b'ff\xe2\x98\x86'], dtype='|S5')
EDIT:事实上,下面公认的答案确实回答了提出的问题,但如果你来这里寻找解决方法,我就是这么做的:
if array.size == 0:
encoded_array = np.chararray((0,))
else:
encoded_array = np.char.encode(a, encoding='utf8')
如果解码的数组为空,这将生成一个带dtype='|S1'
的空编码array.