Skip to main content
 首页 » 编程设计

Python Pandas之累积列

2025年05月04日14Renyi-Fan

我们有这段代码:

import pandas as pd 
depth = {"lastUpdateId":{"0":121305065,"1":121305065,"2":121305065,"3":121305065,"4":121305065,"5":121305065,"6":121305065,"7":121305065,"8":121305065,"9":121305065},"bids":{"0":["0.00152230","8.12000000",[]],"1":["0.00152220","15.74000000",[]],"2":["0.00152210","102.00000000",[]],"3":["0.00152200","59.61000000",[]],"4":["0.00152110","4.44000000",[]],"5":["0.00152100","7.00000000",[]],"6":["0.00152090","165.20000000",[]],"7":["0.00152060","1.92000000",[]],"8":["0.00152030","0.72000000",[]],"9":["0.00152020","267.36000000",[]]},"asks":{"0":["0.00152330","9.86000000",[]],"1":["0.00152460","13.73000000",[]],"2":["0.00152470","109.14000000",[]],"3":["0.00152480","55.54000000",[]],"4":["0.00152500","5.24000000",[]],"5":["0.00152520","5.00000000",[]],"6":["0.00152530","137.45000000",[]],"7":["0.00152550","20.63000000",[]],"8":["0.00152770","892.00000000",[]],"9":["0.00152780","267.36000000",[]]}} 
depthdf = pd.DataFrame(depth) 
depthdf["CummBidsUSD"] = "??" 
depthdf["CummAsksUSD"] = "??" 
USDprice = 7000 
print(depthdf) 

返回这个:

   lastUpdateId                            bids                            asks CummBidsUSD CummAsksUSD 
0     121305065    [0.00152230, 8.12000000, []]    [0.00152330, 9.86000000, []]          ??          ?? 
1     121305065   [0.00152220, 15.74000000, []]   [0.00152460, 13.73000000, []]          ??          ?? 
2     121305065  [0.00152210, 102.00000000, []]  [0.00152470, 109.14000000, []]          ??          ?? 
3     121305065   [0.00152200, 59.61000000, []]   [0.00152480, 55.54000000, []]          ??          ?? 
4     121305065    [0.00152110, 4.44000000, []]    [0.00152500, 5.24000000, []]          ??          ?? 
5     121305065    [0.00152100, 7.00000000, []]    [0.00152520, 5.00000000, []]          ??          ?? 
6     121305065  [0.00152090, 165.20000000, []]  [0.00152530, 137.45000000, []]          ??          ?? 
7     121305065    [0.00152060, 1.92000000, []]   [0.00152550, 20.63000000, []]          ??          ?? 
8     121305065    [0.00152030, 0.72000000, []]  [0.00152770, 892.00000000, []]          ??          ?? 
9     121305065  [0.00152020, 267.36000000, []]  [0.00152780, 267.36000000, []]          ??          ?? 

我们想添加以美元为单位的累计买价和卖价。

为此,我们需要先乘以:assetprice * qty * USDprice

第 0 行的出价示例:0.00152230 * 8.12000000 * 7000

然后添加累计。

我们该怎么做?

请您参考如下方法:

假设 bids 和 asks 的计算方式相同,调用 applymap + cumsum:

depthdf[['bids', 'asks']].applymap( 
    lambda x: float(x[0]) * float(x[1]) * usdprice).cumsum() 
 
          bids          asks 
0    86.527532    105.138166 
1   254.243528    251.667472 
2  1341.022928   1416.507778 
3  1976.107868   2009.319522 
4  2023.383656   2065.256522 
5  2097.912656   2118.638522 
6  3856.681416   3586.205917 
7  3877.118280   3806.503372 
8  3884.780592  13345.462172 
9  6729.865296  16204.770428