将字符串转换为 numpy 数组 python
convert string to numpy array python
我有一个这样的字符串:
'[[-1. ]
[ 4.5]
[ 0. ]]
[[ 8.]
[ 0.]
[ 6.]]
[[ 0. ]
[ 4. ]
[ 0.66666667]]'
我想像这样转换成 NumPy 数组
array([[[-1. ],
[ 4.5 ],
[ 0. ]],
[[ 8. ],
[ 0. ],
[ 6. ]],
[[ 0. ],
[ 4. ],
[ 0.66666667]]])
我尝试了这段代码,但没有得到我的答案
np.array(list(string.replace(']','],')))
如果你事先知道尺码那么
np.fromstring(
s.replace('[', '').replace(']','').replace('\n', ''),
dtype=float, sep=' ').reshape(3,3)
测试用例:
s = '''[[-1. ]
[ 4.5]
[ 0. ]]
[[ 8.]
[ 0.]
[ 6.]]
[[ 0. ]
[ 4. ]
[ 0.66666667]]'''
np.fromstring(
s.replace('[', '').replace(']','').replace('\n', ''),
dtype=float, sep=' ').reshape(3,3)
输出:
array([[-1. , 4.5 , 0. ],
[ 8. , 0. , 6. ],
[ 0. , 4. , 0.66666667]])
我有一个这样的字符串:
'[[-1. ]
[ 4.5]
[ 0. ]]
[[ 8.]
[ 0.]
[ 6.]]
[[ 0. ]
[ 4. ]
[ 0.66666667]]'
我想像这样转换成 NumPy 数组
array([[[-1. ],
[ 4.5 ],
[ 0. ]],
[[ 8. ],
[ 0. ],
[ 6. ]],
[[ 0. ],
[ 4. ],
[ 0.66666667]]])
我尝试了这段代码,但没有得到我的答案
np.array(list(string.replace(']','],')))
如果你事先知道尺码那么
np.fromstring(
s.replace('[', '').replace(']','').replace('\n', ''),
dtype=float, sep=' ').reshape(3,3)
测试用例:
s = '''[[-1. ]
[ 4.5]
[ 0. ]]
[[ 8.]
[ 0.]
[ 6.]]
[[ 0. ]
[ 4. ]
[ 0.66666667]]'''
np.fromstring(
s.replace('[', '').replace(']','').replace('\n', ''),
dtype=float, sep=' ').reshape(3,3)
输出:
array([[-1. , 4.5 , 0. ],
[ 8. , 0. , 6. ],
[ 0. , 4. , 0.66666667]])