将numpy中的int数组转换为字符串数组而不会被截断 [英] Converting int arrays to string arrays in numpy without truncation

查看:67
本文介绍了将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')

这篇关于将numpy中的int数组转换为字符串数组而不会被截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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