将字符串更改为逗号分隔的numpy int数组

2024-10-06 12:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以字节为单位的字符串,里面有逗号。你知道吗

例如b'-8 ,0 ,54 ,-30 ,28'

我首先用

msg = str(msg, 'utf-8')

这部分起作用。但是我需要把这个字符串变成一个numpyint数组。我试过在逗号处拆分,但最后只得到一个一维numpy数组。我希望数组中的每个值都用逗号分隔。你知道吗

msg = str(msg, 'utf-8')

z = [x.strip() for x in msg.split(',')]

x = np.array(z)
y = x.astype(np.int)

我得到的错误是

ValueError: Error when checking input: expected dense_1_input to have shape (5,) but got array with shape (1,)

谢谢你的帮助!你知道吗


Tags: 字符串numpyinput字节np单位msg数组
2条回答
In [213]: b'-8 ,0 ,54 ,-30 ,28'.decode()                                                                     
Out[213]: '-8 ,0 ,54 ,-30 ,28'
In [214]: b'-8 ,0 ,54 ,-30 ,28'.decode().split(',')                                                          
Out[214]: ['-8 ', '0 ', '54 ', '-30 ', '28']
In [215]: np.array(b'-8 ,0 ,54 ,-30 ,28'.decode().split(','), dtype=int)                                     
Out[215]: array([ -8,   0,  54, -30,  28])
In [216]: np.array(b'-8 ,0 ,54 ,-30 ,28'.decode().split(','), dtype=int).reshape(-1,1)                       
Out[216]: 
array([[ -8],
       [  0],
       [ 54],
       [-30],
       [ 28]])

您所缺少的只是列表中从字符串到int的转换:

msg = str(msg, 'utf-8')
z = [int(x.strip()) for x in msg.split(',')]
x = np.array(z)

split()返回一个字符串数组,因此将z作为一个看起来像数字的字符串数组。int()能够将这些字符串转换为它们的数字表示形式。你知道吗

相关问题 更多 >