python - 将字符串更改为逗号分隔的 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,)
感谢您的帮助!
解决方案
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]])
推荐阅读
- c++ - 为什么我不能将运算结果乘以常数特征张量数组
- c++ - 在 mac 上的 Visual Studio 代码中设置 C++
- c++ - Poco.Crypto 库在构建 Poco 时未链接到 libssl.so。为什么?
- c# - 如何修复错误:'Web api 在 iis 上发布后从 SQL Server 获取数据时显示空白页'
- c# - 如何存储 Android 设备令牌?
- python - 这个程序用 Python 写的过程是怎样的?
- fullcalendar - 从完整日历中获取周数
- python - 为什么'a operator= b'在Python中比'a = a operator b'相对快一点?
- java - 有servlet Url:localhost:8080/nameWeb/login时Spring安全登录表单不起作用
- pyspark - 如何用字典替换pyspark数据框列值