将numpy中的int数组转换为字符串数组而不会被截断
问题描述:
尝试将int数组转换为numpy中的字符串数组
Trying to convert int arrays to string arrays in numpy
In [66]: a=array([0,33,4444522])
In [67]: a.astype(str)
Out[67]:
array(['0', '3', '4'],
dtype='|S1')
不是我想要的
In [68]: a.astype('S10')
Out[68]:
array(['0', '33', '4444522'],
dtype='|S10')
这行得通,但我必须知道10个足以容纳我最长的琴弦.有没有一种方法可以轻松地做到这一点,而无需提前知道您需要什么大小的字符串?只是在不引发错误的情况下悄悄地截断字符串似乎有些危险.
This works but I had to know 10 was big enough to hold my longest string. Is there a way of doing this easily without knowing ahead of time what size string you need? It seems a little dangerous that it just quietly truncates your string without throwing an error.
答
同样,这可以在纯Python中解决:
Again, this can be solved in pure Python:
>>> map(str, [0,33,4444522])
['0', '33', '4444522']
或者如果您需要来回转换:
Or if you need to convert back and forth:
>>> a = np.array([0,33,4444522])
>>> np.array(map(str, a))
array(['0', '33', '4444522'],
dtype='|S7')