考虑一下你有一些不均匀的时间序列数据:
import pandas as pd
import random as randy
ts = pd.Series(range(1000),index=randy.sample(pd.date_range('2013-02-01 09:00:00.000000',periods=1e6,freq='U'),1000)).sort_index()
print ts.head()
2013-02-01 09:00:00.002895 995
2013-02-01 09:00:00.003765 499
2013-02-01 09:00:00.003838 797
2013-02-01 09:00:00.004727 295
2013-02-01 09:00:00.006287 253
Run Code Online (Sandbox Code Playgroud)
假设我想在1毫秒的窗口上进行滚动总和来得到这个:
2013-02-01 09:00:00.002895 995
2013-02-01 09:00:00.003765 499 + 995
2013-02-01 09:00:00.003838 797 + 499 + 995
2013-02-01 09:00:00.004727 295 + 797 + 499
2013-02-01 09:00:00.006287 253
Run Code Online (Sandbox Code Playgroud)
目前,我把所有东西都重新投入了多头并在cython中完成,但这在纯大熊猫中是否可行?我知道你可以做类似.asfreq('U')之类的东西,然后填充并使用传统的功能,但是一旦你拥有超过玩具的行数,这就无法扩展.
作为参考,这是一个hackish,而不是快速的Cython版本:
%%cython
import numpy as np
cimport cython
cimport numpy as np
ctypedef np.double_t DTYPE_t
def rolling_sum_cython(np.ndarray[long,ndim=1] times, np.ndarray[double,ndim=1] to_add, long window_size):
cdef …Run Code Online (Sandbox Code Playgroud) 我想快速填写尽可能少的副本,我从C逐渐收到一长串结构.
如果我的结构只是主要数据类型,如下所示:
cdef packed struct oh_hi:
int lucky
char unlucky
Run Code Online (Sandbox Code Playgroud)
然后以下工作正常:
DEF MAXPOWER = 1000000
cdef oh_hi * hi2u = <oh_hi *>malloc(sizeof(oh_hi)*MAXPOWER)
cdef oh_hi [:] hi2me = <oh_hi[:MAXPOWER]> hi2u
Run Code Online (Sandbox Code Playgroud)
但是一旦我改变我的结构来保存一个字符数组:
cdef packed struct oh_hi:
int lucky
char unlucky[10]
Run Code Online (Sandbox Code Playgroud)
之前的memoryview转换编译,但运行时给出:
ValueError: Expected 1 dimension(s), got 1
Run Code Online (Sandbox Code Playgroud)
在Cython中有一个简单的方法吗?我知道我可以创建一个结构化数组,但afaik,这不会让我直接将C结构分配给它.
所以,如果你有一个头文件。
%%file test.h
struct mystruct{
int i;
int j;
};
Run Code Online (Sandbox Code Playgroud)
然后你将它包装在 Cython 中:
cdef extern from "test.h" nogil:
struct mystruct:
int i
int j
Run Code Online (Sandbox Code Playgroud)
还有一些返回到 Py 的函数:
def spit_out_dict():
return mystruct(5,10)
Run Code Online (Sandbox Code Playgroud)
Cython 正确地自动生成一个 dict 包装器。但是,当我将原始 C 标头包装在命名空间中时,我无法让 Cython 仍然正确生成 dict 包装器,如下所示:
%%file test2.h
namespace outerspace{
struct mystruct{
int i;
int j;
};
}
Run Code Online (Sandbox Code Playgroud)
和 Cython/Python:
cdef extern from "test2.h" namespace "outerspace" nogil:
struct mynewstruct:
int i
int j
def spit_out_dict():
return mynewstruct(5,10)
Run Code Online (Sandbox Code Playgroud)
这不会编译 - 很多命名空间投诉错误 - 以前有人遇到过这种情况吗?
即使非常小的简单整数数组也会看到奇怪的行为.
%%cython
import numpy as np
cimport cython
cimport numpy as np
def hi():
DEF MAX = 10000000
cdef int a[MAX],i
cdef int[:] a_mv = a
Run Code Online (Sandbox Code Playgroud)
这会崩溃,但对较小视图的观看会影响我的观看.这不是一个明显的内存问题,因为有足够的内存可用于1000万个内存......