繁体   English   中英

将字符串转换为 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)

Output:

array([[-1.        ,  4.5       ,  0.        ],
       [ 8.        ,  0.        ,  6.        ],
       [ 0.        ,  4.        ,  0.66666667]])

暂无
暂无

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

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