Skip to content

PyObject to NDArray #411

Closed
Closed

Description

@aaronavi

Hi
I have a PyObject which is of a PyDict type, It contains an NDArray, i need to convert it to actual NDArray.

How can i do that?

Thanks

Activity

  1. Nucs commented on Sep 7, 2026

    @Nucs
    Member

    @aaronavi, sorry for the very late reply. With the new NumSharp.Interop.pythonnet package (0.70.0, #628) you can pull the array straight out of the dict.

    Set up the Python engine once at startup - either point pythonnet at an installed Python, or deploy one from NuGet with Python.Included (no system install needed):

    using NumSharp;
    using NumSharp.Interop.PythonNet;
    using Python.Runtime;
    
    // Option A - existing Python: the PYTHONNET_PYDLL env var, or the DLL directly
    Runtime.PythonDLL = "python312.dll";   // or Environment.GetEnvironmentVariable("PYTHONNET_PYDLL")
    PythonEngine.Initialize();
    
    // Option B - deploy an embedded Python from NuGet (dotnet add package Python.Included)
    await Python.Included.Installer.SetupPython();
    await Python.Included.Installer.PipInstallModule("numpy");
    PythonEngine.Initialize();

    Explicit:

    using (Py.GIL())
    {
        // pyDict is your PyObject (a Python dict) holding a numpy array
        PyObject arr = pyDict["weights"];   // the ndarray, still a PyObject
        NDArray nd = arr.AsNDArray();        // -> NumSharp NDArray
        Console.WriteLine(nd.shape[0]);      // 4
    }

    Implicit (register the codec once, then use pythonnet's own As<NDArray>()):

    NDArrayPythonInterop.RegisterCodec();   // once per process
    
    using (Py.GIL())
    {
        PyObject arr = pyDict["weights"];
        NDArray nd = arr.As<NDArray>();      // implicit decode via the codec
        Console.WriteLine(nd.shape[0]);      // 4
    }

    Requires NumSharp.Interop.pythonnet (dotnet add package NumSharp.Interop.pythonnet). Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions