读取打印的numpy数组 [英] Read printed numpy array

查看:99
本文介绍了读取打印的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时提供打印的numpy数组以共享数据,例如这篇文章.到目前为止,我手动进行了转换.但是帖子中的数组太大,无法手动转换.

Sometimes the printed numpy array is provide to share the data such as this post. So far, I converted that manually. But the array in the post is too big to convert by hand.

我想将numpy数组的字符串表示形式转换回数组. (感谢@LevLevitsky.我引用了您的表情.)

I want to convert a string representation of a numpy array back to an array. (Thanks, @LevLevitsky. I reference your expression.)

我尝试了这段代码

import numpy as np

print np.array([[0, 1], [2, 3]])
#[[0 1]
# [2 3]]

# the output is
output = '''[[0 1]
 [2 3]]'''

import re
pat_ignore = re.compile(r'[\[\]]')
numbers = pat_ignore.sub('', output)
print np.array([map(float, line.split()) for line in numbers.splitlines()])
[[ 0.  1.]
 [ 2.  3.]]

但是,这不能保留数据类型.同样,如果ndim > 3,它也无法正常工作.

However, this could not retain the data type. Also if ndim > 3, It does not work properly.

[[[0 1]
  [2 3]]]

被解释为

[[ 0.  1.]
 [ 2.  3.]]

推荐答案

您可以使用re处理字符串,然后使用eval()创建数组:

You can use re to treat the string and then create the array using eval():

 import re
 from ast import literal_eval

 import numpy as np

 a = """[[[ 0 1]
          [ 2 3]]]"""
 a = re.sub(r"([^[])\s+([^]])", r"\1, \2", a)
 a = np.array(literal_eval(a))

这篇关于读取打印的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆