Kel*_*ref 9 python finance dataframe pandas
我有一个如下数据框:
Index Return
2008-11-21 0.153419
2008-11-24 0.037421
2008-11-25 0.077500
Run Code Online (Sandbox Code Playgroud)
计算最后一行所有列的累积回报的最佳方法是什么?
以下是预期结果:
Index Return
2008-11-21 0.153419
2008-11-24 0.037421
2008-11-25 0.077500
Cumulative 0.289316
Run Code Online (Sandbox Code Playgroud)
累积回报计算如下:
cumulative = (1 + return1) * (1 + return2) * (1 + return3) - 1
Run Code Online (Sandbox Code Playgroud)
在熊猫中执行此操作的最佳方法是什么?
Ste*_*n G 10
有一个熊猫cumprod()方法.这适用于每一列.
df.ix["Cumulative"] = ((df+1).cumprod()-1).iloc[-1]
Run Code Online (Sandbox Code Playgroud)
这比大型数据集上的其他解决方案快2倍:
In[106]: %timeit df.ix["Cumulative"] = ((df+1).cumprod()-1).iloc[-1]
10 loops, best of 3: 18.4 ms per loop
In[107]: %timeit df.ix['Cummulative'] = df.apply(lambda x: (x+1).prod()-1)
10 loops, best of 3: 32.9 ms per loop
In[110]: %timeit df.append(df.iloc[:,1:].apply(lambda col: (col + 1).prod() - 1), ignore_index=True)
10 loops, best of 3: 37.1 ms per loop
In[113]: %timeit df.append(df.apply(lambda col: prod([(1+c) for c in col]) - 1), ignore_index=True)
1 loop, best of 3: 262 ms per loop
Run Code Online (Sandbox Code Playgroud)
我建议永远不要使用apply如果你能找到一个内置的方法,因为apply循环遍历数据帧,这使得它变慢.Bult-in方法非常高效,通常你不会比使用apply更快.