How to convert a Julia 3D array to a Python 3D list

I have a Julia 3D array on the format Vector{Vector{Vector{Float64}}} and I am wondering how I can convert it into a 3D list in Python with the same indexing.

Thanks for any help!

Is there a reason that your “Julia 3D array” is not an Array{Float64, 3}? Are the internal vectors of different lengths?

By same indexing, do you mean you want 1-based indexing and F-order while in Python?

Why a list rather than a Numpy array?

Just to point out some terminology: this is not a 3d array, but a 1d array, or vector, that happens to contain other vectors. In Julia an N-d array is not nested, but ‘flat’, and with special indexing, eg. X[i, j, k] instead of X[i][j][k], which is how you index a nested vector/list.

I don’t think you can have 1-based indexing in Python, but the nested indexing is the similar.

This does not answer the indexing part of your question, but it covers the basics of invoking Python, convert to a Python list, and evaluating Python code.

julia> begin
           using Pkg
           Pkg.activate(; temp=true)
           Pkg.add("PythonCall")
       end

julia> using PythonCall

julia> ragged_3d = [
           [
               Float64[1,2,],
               Float64[4,5],
           ],
           [
               Float64[6],
               Float64[7,8],
               Float64[9,10,11],
           ],
       ]
2-element Vector{Vector{Vector{Float64}}}:
 [[1.0, 2.0], [4.0, 5.0]]
 [[6.0], [7.0, 8.0], [9.0, 10.0, 11.0]]

julia> py_ragged_3d = pyconvert(PyList, ragged_3d)
2-element PyList{Any}:
 [[1.0, 2.0], [4.0, 5.0]]
 [[6.0], [7.0, 8.0], [9.0, 10.0, 11.0]]

julia> pyprint(py_ragged_3d)
[[[1.0, 2.0], [4.0, 5.0]], [[6.0], [7.0, 8.0], [9.0, 10.0, 11.0]]]

julia> @pyeval (a=py_ragged_3d) => `print(a[0][0][0])`
1.0
Python: None
1 Like

Yes, the internal vectors are of different length. The conversion to python could be to numpy, it is not so important how it is ported over. With same indexing, I mean that the current indexing in julia ( i.e. X[i, j, k]) is maintained into python in the form of X[i][j][k].

I want to save the array as a file and then read it into a Jupyter Notebook.

If you’re saving to a file, use some common data format such as JSON. You can use JSON.jl to write it out and Python’s JSON stdlib to read it.