首页 > 解决方案 > 将字符串更改为逗号分隔的 numpy int 数组

问题描述

我有一个以字节为单位的字符串,其中包含逗号。

前任。b'-8 ,0 ,54 ,-30 ,28'

我首先使用将其更改为字符串

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

这部分有效。但是我需要把这个字符串变成一个 numpy int 数组。我试过用逗号分割,但我最终得到了一个一维 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,)

感谢您的帮助!

标签: pythonpython-3.xnumpy

解决方案


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

推荐阅读