我有一个熊猫数据框以下格式在日期的区别:计算在熊猫的GroupBy对象
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”是*不是最大的。 –
2015-01-09和2015-01-01之间的差异为8天。 2015-01-10和2015-01-09之间的差异为1天。在这种情况下,我有兴趣获取对应于2015-01-01日期的“col2”的值,因为差异最大。 – invoker
哦,所以你的意思是在同一组中的前一行。我不得不说这个问题是非常不清楚的。此外,它是未定义的大小为1的组。 –