繁体   English   中英

成对计算 pandas 行之间的差异

[英]calculate the difference between pandas rows in pairs

我有一个 dataframe 的订单如下,其中“价值”列代表现金进出,“日期”列反映交易发生的时间。

每笔交易都是分组的,因此“QTY”输出总是由“QTY”“输入”成功,由“QTY”列中的符号反映:

    Date       Qty  Price       Value       
0   2014-11-18  58  495.775716  -2875499    
1   2014-11-24 -58  484.280147  2808824    
2   2014-11-26  63  474.138699  -2987073  
3   2014-12-31 -63  507.931247  3199966    
4   2015-01-05  59  495.923771  -2925950    
5   2015-02-05 -59  456.224370  2691723   

如何创建两列“n_days”和“price_diff”,即每笔交易的两个日期与“价值”之间的天数差?

我努力了:

df['price_diff'] = df['Value'].rolling(2).apply(lambda x: x[0] + x[1])

但收到第一次观察的关键错误(0)。

非常感谢

你为什么不直接使用sum

df['price_diff'] = df['Value'].rolling(2).sum()

虽然从名字上看,

df['price_diff'] = df['Price'].diff()

并且,对于两列:

df[['Date_diff','Price_diff']] = df[['Date','Price']].diff()

Output:

        Date  Qty       Price    Value Date_diff  Price_diff
0 2014-11-18   58  495.775716 -2875499       NaT         NaN
1 2014-11-24  -58  484.280147  2808824    6 days  -11.495569
2 2014-11-26   63  474.138699 -2987073    2 days  -10.141448
3 2014-12-31  -63  507.931247  3199966   35 days   33.792548
4 2015-01-05   59  495.923771 -2925950    5 days  -12.007476
5 2015-02-05  -59  456.224370  2691723   31 days  -39.699401

根据评论更新,您可以尝试:

df['Val_sum'] = df['Value'].rolling(2).sum()[1::2]

Output:

        Date  Qty       Price    Value   Val_sum
0 2014-11-18   58  495.775716 -2875499       NaN
1 2014-11-24  -58  484.280147  2808824  -66675.0
2 2014-11-26   63  474.138699 -2987073       NaN
3 2014-12-31  -63  507.931247  3199966  212893.0
4 2015-01-05   59  495.923771 -2925950       NaN
5 2015-02-05  -59  456.224370  2691723 -234227.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM