c# - 将 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 个项目。
解决方案
使用:
npArray = np.fromiter(array, int)
为我工作。
推荐阅读
- c# - 从 JSON 响应创建列表
- java - Intellij 模块
- javascript - 以 ES6 模块语法列出所有导出
- python - pyinstaller 无法构建可执行文件
- mysql - 如何阻止我的日期选择一个额外的日期?
- python - 给定总体和子集,如何创建所有组合的列表?(nCr)
- python - 如何使用正则表达式将单词列表与另一个单词列表进行比较并打印匹配项?
- python - 如何将 Django 模型迁移到具有表继承的模型中
- excel - 我得到的错误是 'If lineod<>"" then' 行上的不匹配类型
- wordpress - 禁用 Wordpress 重定向