减少Pandas中的一列

Isa*_*aac 6 python pandas

我正在尝试将一个(很多,很多)返回数据列转换为收盘价格列.在Clojure中,我会使用reductions,就像reduce,但返回所有中间值的序列.

例如

$ c

0.12
-.13
0.23
0.17
0.29
-0.11

# something like this
$ c.reductions(init=1, lambda accumulator, ret: accumulator * (1 + ret)) 

1.12
0.97
1.20
1.40
1.81
1.61
Run Code Online (Sandbox Code Playgroud)

注意:实际收盘价无关紧要,因此使用1作为初始值.我只需要一个"模拟"收盘价.

我的数据的实际结构是TimeSeries的命名列的DataFrame.我想我正在寻找一个类似的功能applymap,但是我宁愿不做一些hacky这个功能并从中引用DF(我想这是解决这个问题的一个方法吗?)

另外,如果我想保留returns数据,但我的收盘价格是多少呢?我应该返回一个元组,并让TimeSeries属于那个类型(returns, closing_price)吗?

Zel*_*ny7 5

它看起来好像尚未广为人知,但是您可以expanding_apply用来实现收益计算:

In [1]: s
Out[1]:
0    0.12
1   -0.13
2    0.23
3    0.17
4    0.29
5   -0.11

In [2]: pd.expanding_apply(s ,lambda s: reduce(lambda x, y: x * (1+y), s, 1))

Out[2]:
0    1.120000
1    0.974400
2    1.198512
3    1.402259
4    1.808914
5    1.609934
Run Code Online (Sandbox Code Playgroud)

我不确定100%,但是我相信expanding_apply从第一个索引到当前索引,该系列都适用。我使用的内置reduce函数与Clojure函数完全一样。

Docstring expanding_apply

Generic expanding function application

Parameters
----------
arg : Series, DataFrame
func : function
    Must produce a single value from an ndarray input
min_periods : int
    Minimum number of observations in window required to have a value
freq : None or string alias / date offset object, default=None
    Frequency to conform to before computing statistic
center : boolean, default False
    Whether the label should correspond with center of window

Returns
-------
y : type of input argument
Run Code Online (Sandbox Code Playgroud)


And*_*den 4

值得注意的是,用 pandas 写得更详细通常比写成 .pandas 更快(也更容易理解)reduce

在你的具体例子中,我会add然后cumprod

In [2]: c.add(1).cumprod()
Out[2]: 
0    1.120000
1    0.974400
2    1.198512
3    1.402259
4    1.808914
5    1.609934
Run Code Online (Sandbox Code Playgroud)

也许init * c.add(1).cumprod()

注意:但是在某些情况下,例如内存是一个问题,您可能必须以更低级/更聪明的方式重写它们,但通常值得首先尝试最简单的方法(并对其进行测试,例如使用 %timeit 或分析内存)。