Python 将字符串数组转换为numpy数组
我正在尝试将字符串“[0.0.1.]”转换为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("." , '')))
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)