Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read printed numpy array

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.

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

I tried this code

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.]]

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

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

is interpreted as

[[ 0.  1.]
 [ 2.  3.]]
like image 728
emeth Avatar asked May 28 '14 14:05

emeth


1 Answers

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))
like image 129
Saullo G. P. Castro Avatar answered Oct 05 '22 20:10

Saullo G. P. Castro