-
-
Couldn't load subscription status.
- Fork 324
Return numpy array from python to Lazarus #488
-
Hi,
I've recently started playing around with P4D in Lazarus/FPC. I'm trying to read a numpy array created in python back in to FPC. The python code which I have in SynEdit1:
import numpy as np
py_array = np.zeros(10)
for i in range (10):
py_array[i]=i
My attempt at the FPC code below to extract py_array is based on FPC Demo35:
const
N = 10;
type
PIntArray = ^TIntArray;
TIntArray = array[0..N - 1] of NativeInt;
procedure TForm1.Button1Click(Sender: TObject);
var
np_arr: PPyObject;
PyBuffer: Py_buffer;
I:integer;
res:int64;
begin
self.PythonEngine1.ExecStrings(self.SynEdit1.lines);
np_arr := ExtractPythonObjectFrom(MainModule.py_array);
PythonEngine1.PyObject_GetBuffer(np_arr, @PyBuffer, PyBUF_CONTIG);
PythonEngine1.CheckError;
try
for I := 0 to N - 1 do
res:= PIntArray(PyBuffer.buf)^[I];
self.ListBox1.Items.Add(inttostr(res));
finally
PythonEngine1.PyBuffer_Release(@PyBuffer);
end;
end;
However, when I run this, I only end up with a single, random number in ListBox1. Any suggestions on how to resolve this would be greatly appreciated!
Beta Was this translation helpful? Give feedback.
All reactions
If you run this code in PyScripter
import numpy as np py_array = np.zeros(10) for i in range (10): py_array[i]=i print(py_array)
The output is:
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
Notice that the values are floating point and you try to read them as Integers.
I think if you change your code to:
import numpy as np py_array = np.zeros(10, dtype= np.int32) for i in range (10): py_array[i]=i
or simpler:
import numpy as np py_array = np.array(range(10))
it should work.
Replies: 1 comment
-
If you run this code in PyScripter
import numpy as np py_array = np.zeros(10) for i in range (10): py_array[i]=i print(py_array)
The output is:
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
Notice that the values are floating point and you try to read them as Integers.
I think if you change your code to:
import numpy as np py_array = np.zeros(10, dtype= np.int32) for i in range (10): py_array[i]=i
or simpler:
import numpy as np py_array = np.array(range(10))
it should work.
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1