1

I am using pythonnet.netstandatd Nuget package to get some data from C# code to python script. Problem: System.Int32[] is indexable but not an array in python

C# class

namespace MyNamespace
{
    public class MyClass
    {
        public int[] Test()
        {
            return new[]{ 1,2,3 };
        }
    }
}

and python code executed in

using( Py.GIL() )
{
    PythonEngine.Exec( myScriptString );
}
import sys
import numpy as np

# Import C# namespaces and classes
import clr
from MyNamespace import MyClass

myClass = MyClass()
array = myClass.Test()
print( 'Type of array:', type( array ) )
print( 'Length of array:', len( array ) )
print( 'First element of array:', array[0] )

npArray = np.array( array )
print( 'Type of npArray:', type( npArray ) )
print( 'Shape of npArray:', npArray.shape )
print( 'Length of npArray:', len( npArray ) )
print( 'First element of npArray:', npArray[0] )

And I am getting following result:

Type of array: <class 'System.Int32[]'>
Length of array: 3
First element of array: 1
Type of npArray: <class 'numpy.ndarray'>
Shape of npArray: ()
IndexError: too many indices for array

Numpy can create ndarrays from various python collections, and result of myClass.Test() is indexable, has length, but not recognizable as an array. Copying result of myClass.Test() to numpy array one by one is not an option, because it contains around 25 000 000 items.

1 Answer 1

3

Using:

npArray = np.fromiter(array, int)

worked for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.