简体   繁体   中英

for-loop values into a numpy array

Ok, so I have wrapped a C library in Python and called the corresponding DLL's. I then created a for-loop that prints out all the data points. Here is an small sample of my code and the library that I have wrapped:

import ctypes 
from ctypes import * 

class ParmData(Union):
_fields_ = [
         ('c', ctypes.POINTER(ctypes.c_ubyte)),
         ('f', ctypes.POINTER(ctypes.c_float))]
class SParm(Structure):
pass
SParm._fields_ = [
        ('data', ctypes.POINTER(ParmData)),
        ('time', ctypes.POINTER(ctypes.c_float))]

dll.readSParm.argtypes = (POINTER(SFile), c_char_p, c_double, c_double,    c_double, POINTER(TTag), c_ushort,)   
dll.readSParm.restype = POINTER(SParm)
g = dll.readSParm(SF, ParmName, startTime, stopTime, Null, None, convertType)
dll.freeSParm(g)

This is the for-loop that I have created in Python:

for i in range(0, 50000):
print(i, (g[0].data[0].f[i]), (g[0].time[i]))

Where

(g[0].data[0].f)
(g[0].time) 

are pointers to objects that contain all of the data.

the results of the for-loop look like this the second column is data and the third is the corresponding time value for that data:

2 -4864024.0 -1027.21630859375
3 5.114739e-43 -1026.21630859375
4 2.840103e-37 -1025.21630859375
5 2.250064e-38 -1024.21630859375

My question is this:

How can I get this data into a numpy array? Because I have so many data point I cant type them all in.

A dirty (yet easy) way would be to just iterate over the data and fill the array as you go, like so:

data_len = 5000 #<- you should have a way of knowing how much data there is
arr = np.empty([data_len,2],dtype=np.float) #empty array of the right size 
for i in range(data_len): #we fill the array row by row
    arr[i,:]= (g[0].data[0].f[i],g[0].time[i])

print(arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM