【问题标题】:for-loop values into a numpy arrayfor循环值到一个numpy数组中
【发布时间】:2017-07-13 19:36:51
【问题描述】:

好的,所以我在 Python 中封装了一个 C 库并调用了相应的 DLL。然后我创建了一个打印出所有数据点的 for 循环。 这是我的代码和包装的库的一个小示例:

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)

这是我在 Python 中创建的 for 循环:

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

在哪里

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

是指向包含所有数据的对象的指针。

for 循环的结果如下所示,第二列是数据,第三列是该数据对应的时间值:

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

我的问题是这样的:

如何将这些数据放入 numpy 数组中?因为我有太多的数据点,我不能全部输入。

【问题讨论】:

    标签: python arrays numpy for-loop


    【解决方案1】:

    一种肮脏(但很简单)的方法是迭代数据并随时填充数组,如下所示:

    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)
    

    【讨论】:

    • 这行得通,谢谢。好奇你为什么认为它很脏?
    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2019-01-03
    相关资源
    最近更新 更多