Search code examples
pythonrapirpython

Using the rPython package for creating and "getting" a numpy array


I am trying to create a Rpackage that uses some python in it, in an attempt to better understand the rPython package I tried creating and getting back a Numpy Array:

This part works

library(rPython)
python.exec( "import os" )
python.exec( "import numpy as np" )

X = c(0.5, 0.2, 0.2)
python.exec(paste("X0 = np.array([", do.call(paste, c(as.list(X), sep =",")), "])"))

This part does not

But when I try to get back the array it gives me an error:

python.get("X0")

get me

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 244, in dumps
return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")

TypeError: array([0.5, 0.2, 0.2]) is not JSON serializable

Any idea of what I am doing wrong?


Solution

  • You need to convert your numpy array to a json serializable object. This can be done using the tolist() method. Witness:

    >>> X0 = np.array([0,0])
    >>> import json
    >>> X0.tolist()
    [0, 0]
    >>> json.dumps(X0.tolist())
    '[0, 0]'
    

    Hope that helps.