首页 > 解决方案 > 将 System.Int32[] 从 pythonnet.netstandard 转换为 python 脚本中的 numpy 数组

问题描述

我正在使用 pythonnet.netstandatd Nuget 包从 C# 代码获取一些数据到 python 脚本。问题:System.Int32[] 是可索引的,但在 python 中不是数组

C# 类

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

和执行的python代码

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] )

我得到以下结果:

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 可以从各种 python 集合创建 ndarray,myClass.Test() 的结果是可索引的,有长度,但不能识别为数组。将 myClass.Test() 的结果一个一个复制到 numpy 数组不是一种选择,因为它包含大约 25 000 000 个项目。

标签: c#pythonnumpypython.net

解决方案


使用:

npArray = np.fromiter(array, int)

为我工作。


推荐阅读