简体   繁体   English

Pandas Groupby将功能应用于关卡

[英]Pandas Groupby Apply Function to Level

I have a pandas groupby object that has the following structure: 我有一个pandas groupby对象具有以下结构:

SETTLE_DATE  DATE
2014-09-23   2014-09-19    0.000091
             2014-09-22    0.000163
2014-10-01   2014-09-29   -0.000002
2014-11-13   2014-08-29    0.007774
             2014-09-01    0.008993
             2014-09-02    0.010048
             2014-09-03    0.009496
             2014-09-04    0.015213
             2014-09-05    0.015772
             2014-09-08    0.016733
             2014-09-09    0.018464
             2014-09-10    0.018361
             2014-09-11    0.017473
             2014-09-12    0.017884
             2014-09-15    0.017860
             2014-09-16    0.017706
             2014-09-17    0.016628
             2014-09-18    0.017866
             2014-09-19    0.020719
             2014-09-22    0.021473
             2014-09-23    0.020296
             2014-09-24    0.022314
             2014-09-25    0.024007
             2014-09-26    0.026014
             2014-09-29    0.026411

How do I subtract the first DATE from the last DATE for each SETTLE_DATE ? 如何从每个SETTLE_DATE的最后一个DATE减去第一个DATE

For instance, I would like to subtract 2014-08-29 .007774 from 2014-09-29 0.026411 , and repeat the same thing for settle dates 2014-10-01 and 2014-09-23 例如,我想从2014-09-29 0.026411减去2014-08-29 .007774 ,并重复2014-10-012014-09-23结算日期

As a suggestion, if you paste your data as an easily copy-pasteable format (eg df.to_dict() ), you'll probably get a faster response. 作为建议,如果您将数据粘贴为易于复制粘贴的格式(例如df.to_dict() ),您可能会得到更快的响应。

Assuming you have a series s , with a MultiIndex andthe two levels you have shown, you can groupby the first level and apply the 'first' / 'last' aggregations to get the values you want. 假设你有一个系列s ,具有多指标,你已经证明并且所述两个层次,你可以GROUPBY第一级和应用的'first' / 'last'聚合得到你想要的值。

In [136]: s.groupby(level=0).agg('last') - s.groupby(level=0).agg('first')
Out[136]: 
SETTLE_DATE
2014-09-23     0.000072
2014-10-01     0.000000
2014-11-13     0.018637
Name: VALUE, dtype: float64

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

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