Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串数组转换为numpy数组_Python_Numpy - Fatal编程技术网

Python 将字符串数组转换为numpy数组

Python 将字符串数组转换为numpy数组,python,numpy,Python,Numpy,我正在尝试将字符串“[0.0.1.]”转换为numpy数组 这是我写的代码,但是需要更复杂的代码吗 arr = [] s = '[ 0. 0. 1.]' arr.append(int(s.split(" ")[1].replace("." , ''))) arr.append(int(s.split(" ")[3].replace("." , ''))) arr.append(int(s.split(" ")[5].replace("]" , '').replace("." , '')))

我正在尝试将字符串“[0.0.1.]”转换为numpy数组

这是我写的代码,但是需要更复杂的代码吗

arr = []
s = '[ 0.  0.  1.]'
arr.append(int(s.split(" ")[1].replace("." , '')))
arr.append(int(s.split(" ")[3].replace("." , '')))
arr.append(int(s.split(" ")[5].replace("]" , '').replace("." , '')))

arr = np.array(arr)

print(arr)
print(type(arr))
print(type(arr[0]))
以上代码打印:

[0 0 1]
<class 'numpy.ndarray'>
<class 'numpy.int64'>
是否有更干净的方法将字符串“[0.0.1.]”转换为numpy int数组类型?

中:

import numpy as np

s = '[ 0.  0.  1.]'

out = np.array([int(i.replace('.','')) for i in s[s.find('[')+1:s.find(']')].split()])

print(type(out))
输出:


Numpy as比所有答案更容易处理:

s = '[ 0.  0.  1.]'
np.fromstring(s[1:-1],sep=' ').astype(int)

这取决于你想要多灵活。数组[1:-1]。拆分、浮点.astypeintor偶数np.matrixs.A1。astypeint@PaulPanzers='[0.0.1.]'np.matrixs returns'TypeError:提供的数据字符串无效:[“奇怪,它对我有效。您使用的是哪个版本?看起来它在1.13.x期间的某个时候发生了更改。因此,如果您是1.12或更低,则必须执行np.matrixs[1:-1].A1.astypeint
s = '[ 0.  0.  1.]'
np.fromstring(s[1:-1],sep=' ').astype(int)