我正在使用 pythonnet 在 C# 中使用 numpy。我想重塑一个数组,但它似乎不起作用,我似乎无法理解为什么。起初我以为复杂数组有问题,但后来我用 int 尝试了一下,结果是一样的
这是代码
using System.Numerics;
using Python.Runtime;
static void Initialize()
{
string pythonDll = @"C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\python39.dll";
Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", pythonDll);
PythonEngine.Initialize();
}
Initialize();
Complex[] complexes = [
new Complex(1.0, 2.0),
new Complex(3.0, 4.0),
new Complex(5.0, 6.0),
new Complex(5.0, 6.0)
];
List<Complex> comlist = new List<Complex>(complexes);
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
dynamic rawData = np.array(comlist);
np.reshape(a: rawData.T, newshape:(2, 2), order:'F');
}
和错误消息:
Unhandled exception. Python.Runtime.PythonException: expected sequence object with len >= 0 or a single integer
File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\fromnumeric.py", line 44, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\fromnumeric.py", line 67, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\fromnumeric.py", line 299, in reshape
return _wrapfunc(a, 'reshape', newshape, order=order)
File "<__array_function__ internals>", line 5, in reshape
at Python.Runtime.PythonException.ThrowLastAsClrException()
at Python.Runtime.PyObject.Invoke(PyTuple args, PyDict kw)
at Python.Runtime.PyObject.InvokeMethod(String name, PyTuple args, PyDict kw)
at Python.Runtime.PyObject.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
at CallSite.Target(Closure, CallSite, Object, Object, ValueTuple`2, Char)
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid4[T0,T1,T2,T3](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
at Program.<Main>$(String[] args) in C:\Users\Mohsen\RiderProjects\ConsoleApp2\ConsoleApp2\Program.cs:line 29
重塑大小必须是 PyTuple 对象才能工作,否则就不是这样了。