计算 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的值,我们需要用groupby来计算。这可以通过将函数应用于以下内容来实现吗?请注意,日期已经按升序排列。

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

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

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

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

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) 处理了这样一个事实,即您想要相差最大的两个连续日期中的第一个日期。