2015-06-08 72 views
3

我有一个熊猫数据框以下格式在日期的区别:计算在熊猫的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 

真正dfcol1,我们需要GROUPBY做很多计算值的组。这是可能的通过应用以下功能?请注意,日期已经是升序。

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

所以,正如我在我的回答中指出的那样,我认为你在这个问题上有一个错误:“2015-01-09 - 2015-01-01”是*不是最大的。 –

+0

2015-01-09和2015-01-01之间的差异为8天。 2015-01-10和2015-01-09之间的差异为1天。在这种情况下,我有兴趣获取对应于2015-01-01日期的“col2”的值,因为差异最大。 – invoker

+0

哦,所以你的意思是在同一组中的前一行。我不得不说这个问题是非常不清楚的。此外,它是未定义的大小为1的组。 –

回答

2

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

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 
+0

您编写的'lambda'函数将查找**最大日期**并返回与该日期相对应的'col2'的值。这不是我们想要的(如果我想要的话,我可以查看每个组中的最后一行,因为日期已经排序)。 **我需要在行操作之间做一个查找日期差异的操作,并且最大限度地找到'col2'的值。** – invoker

+0

我以前的评论已过时,代码自那时以来一直在改变。 阿美,我认为你做到了!谢谢一堆! – invoker

+0

Ami,我有一堆麻烦让这个工作DateTime类型。你能帮我吗?它适用于整数,但这对我来说只是一步。 – invoker

3

我会尝试一个稍微不同的方法:旋转表格,以便为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)需要的是你要首先用最大差值的两个连续日期的事实照顾。