Warm tip: This article is reproduced from stackoverflow.com, please click
arrays numpy python python-3.x r

Save a 3 dimensional array from R to a format to be read by Python numpy

发布于 2020-03-29 20:59:45

I have a 3-dimensional array in R (numerical), which I want to transfer to Python, i.e. to a 3-dimensional numpy array. How can I do this? I have tried several options, but all of them destroy the 3rd dimension.

Questioner
D1X
Viewed
49
StupidWolf 2020-01-31 18:54

Try reticulate to convert the array from R to python. Then save it using numpy (called from within R).

## inside R

library(reticulate)
x = array(runif(27),dim=c(3,3,3))
# import numpy
np = import("numpy")
np$save("test.npy",r_to_py(x))

Now we load it with python:

import numpy as np                                                      
np.load("test.npy")                                                     
array([[[0.53035511, 0.09324333, 0.74165792],
        [0.32596559, 0.84278233, 0.63397294],
        [0.71819993, 0.69992033, 0.23523802]],

       [[0.4240157 , 0.92849409, 0.23161098],
        [0.82145088, 0.789411  , 0.18161145],
        [0.87357443, 0.29713062, 0.35034028]],

       [[0.17399566, 0.81314384, 0.92519895],
        [0.72759271, 0.62621744, 0.02139281],
        [0.39817859, 0.62391164, 0.66426406]]])