【发布时间】:2015-08-23 07:57:15
【问题描述】:
我有一个格式如下的 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)
【问题讨论】:
-
所以,正如我在回答中指出的那样,我认为您的问题有误:“2015-01-09 - 2015-01-01”是 not最棒的。
-
2015-01-09 和 2015-01-01 相差 8 天。 2015-01-10 和 2015-01-09 之间的差异是 1 天。在这种情况下,我有兴趣捕获对应于 2015-01-01 日期的
col2的值,因为差异最大。 -
哦,你的意思是在同一个 groupby 中的前一行。我不得不说这个问题非常不清楚。此外,它是大小为 1 的未定义组。
-
此操作仅适用于原始数据框中大于 2 的组。
-
好吧,更新了问题和答案以反映这一点。我必须说我认为措辞可以改进,尤其是。因为未明确表示长度 = 1 组的未定义结果。
标签: python pandas time-series