繁体   English   中英

计算Pandas GroupBy对象中日期的差异

[英]Calculating the difference in dates in a Pandas GroupBy object

我有一个Pandas DataFrame,格式如下:

In [0]: df
Out[0]: 
       col1  col2       date
 0     1     1          2015-01-01
 1     1     2          2015-01-09
 2     1     3          2015-01-10
 3     2     1          2015-02-10
 4     2     2          2015-02-10
 5     2     3          2015-02-25

In [1]: df.dtypes
Out[1]:
 col1             int64
 col2             int64
 date    datetime64[ns]
 dtype: object

我们希望找到col2的值,该值对应于日期中最大的差异(按日期排序组中的连续元素之间),按col1分组。 假设没有大小为1的组。

期望的输出

In [2]: output
Out[2]:
col1   col2
1      1         # This is because the difference between 2015-01-09 and 2015-01-01 is the greatest
2      2         # This is because the difference between 2015-02-25 and 2015-02-10 is the greatest

真正的df有很多col1值,我们需要将它们分组才能进行计算。 这可以通过应用以下功能来实现吗? 请注意,日期已按升序排列。

gb = df.groupby(col1)
gb.apply(right_maximum_date_difference)

我会尝试稍微不同的方法:转动表格,以便为col2中的每个值都有一个列, col2包含日期和col1的值作为索引。 然后,您可以使用.diff方法来获取连续单元格之间的差异。 如果存在重复的col1col2对,这可能不起作用,这在问题中并不清楚。

df = pd.DataFrame({'col1': [1, 1, 1, 2, 2, 2],
          'col2': [1, 2, 3, 1, 2, 3],
          'date': pd.to_datetime(['2015-01-01', '2015-01-09', '2015-01-10', 
                                  '2015-02-10', '2015-02-10', '2015-02-25'])})
p = df.pivot(columns='col1', index='col2', values='date')
p
    col1    1   2
col2        
1   2015-01-01  2015-02-10
2   2015-01-09  2015-02-10
3   2015-01-10  2015-02-25

p.diff().shift(-1).idxmax() 

col1
1       1
2       2

.shift(-1)负责处理两个连续日期中第一个具有最大差异的事实。

这里几乎是你的数据帧(我避免复制日期):

df = pd.DataFrame({
    'col1': [1, 1, 1, 2, 2, 2],
    'col2': [1, 2, 3, 1, 2, 3],
    'date': [1, 9, 10, 10, 10, 25]
})

有了这个,定义:

def max_diff_date(g):
    g = g.sort(columns=['date'])
    return g.col2.ix[(g.date.ix[1: ] - g.date.shift(1)).argmax() - 1]

你有:

>> df.groupby(df.col1).apply(max_diff_date)
col1
1    1
2    2
dtype: int64

暂无
暂无

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

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