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

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

问题描述

尝试将 numpy 中的 int 数组转换为字符串数组

在[66]中:a=array([0,33,4444522])在 [67] 中:a.astype(str)出[67]:数组(['0', '3', '4'],dtype='|S1')

不是我想要的

在[68]中:a.astype('S10')出[68]:数组(['0','33','4444522'],dtype='|S10')

这行得通,但我必须知道 10 的大小足以容纳我最长的字符串.有没有一种方法可以在不提前知道您需要什么尺寸的字符串的情况下轻松做到这一点?它只是悄悄地截断你的字符串而不抛出错误,这似乎有点危险.

解决方案

同样,这可以在纯 Python 中解决:

<预><代码>>>>地图(字符串,[0,33,4444522])['0'、'33'、'4444522']

或者如果您需要来回转换:

<预><代码>>>>a = np.array([0,33,4444522])>>>np.array(map(str, a))数组(['0','33','4444522'],dtype='|S7')

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')

Not what I intended

In [68]: a.astype('S10')
Out[68]: 
array(['0', '33', '4444522'], 
      dtype='|S10')

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.

解决方案

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天全站免登陆