计算Pandas GroupBy对象中日期的差异
问题内容:
我有以下格式的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)
问题答案:
这几乎是您的数据框(我避免了复制日期):
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