简体   繁体   English

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

[英]Changing a string into a comma separated numpy int array

I have a string that comes in bytes that has commas inside of it.我有一个以字节为单位的字符串,其中包含逗号。

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

I first change it into a string using我首先使用

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

This part works.这部分有效。 However I need to make this string into a numpy int array.但是我需要把这个字符串变成一个 numpy int 数组。 I have tried splitting at the commas, but I wind up just getting a 1 dimensional numpy array.我试过用逗号分割,但我最终得到了一个一维的 numpy 数组。 I would like for each value in the array to be split by a comma.我希望数组中的每个值都用逗号分隔。

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

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

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

The error I get is我得到的错误是

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

Thank for the help!感谢您的帮助!

All you are missing is a conversion from a string to an int inside of your list comprehension:您所缺少的只是列表理解中从字符串到 int 的转换:

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

split() returns an array of strings, so you were getting z as an array of strings that look like numbers. split()返回一个字符串数组,因此您将z作为一个看起来像数字的字符串数组。 int() is able to convert such strings into their numerical representations. int()能够将这些字符串转换为它们的数字表示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM