简体   繁体   English

使用rPython包创建和“获取” numpy数组

[英]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: 我正在尝试创建一个在其中使用某些python的Rpackage,以更好地了解我尝试创建并取回一个Numpy数组的rPython软件包:

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 TypeError:array([0.5,0.2,0.2])不可序列化JSON

Any idea of what I am doing wrong? 任何我做错事的想法吗?

You need to convert your numpy array to a json serializable object. 您需要将numpy数组转换为json可序列化对象。 This can be done using the tolist() method. 这可以使用tolist()方法完成。 Witness: 见证人:

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

Hope that helps. 希望能有所帮助。

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

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