Pandas基于日期的分组以在条件上返回行

时间:2017-09-19 07:28:56

标签: python pandas dataframe

我有一个数据框,其数据类似于

1. id       date                   remarks
2. 1       12-01-2015 12:00:15     Good
3. 2       12-01-2015 1:00:14      OK
4. 1       13-01-2015 12:00:15     Not Ok
5. 2       14-01-2015 1:00:15      Bad
6. 3       15-01-2015 1:00:15      Good

我需要以这样的方式输出:对于每个id,返回最高日期和备注,因此对于id 2,它将返回14-01-2015 1:00:15并且备注为坏

2 个答案:

答案 0 :(得分:2)

您需要sort_values + groupby + GroupBy.last

df['date'] = pd.to_datetime(df['date'], dayfirst=True)

df1 = df.sort_values('date').groupby('id', as_index=False).last()
print (df1)
   id                date remarks
0   1 2015-01-13 12:00:15  Not Ok
1   2 2015-01-14 01:00:15     Bad
2   3 2015-01-15 01:00:15    Good

答案 1 :(得分:2)

我希望您的日期列采用第一种格式,如果是这样,您需要groupby id idxmax date loc,然后从dayfirst重新使用抬头。如果它不是idxmin()格式,那么df.loc[df.groupby('id')['date'].idxmax()] 将有助于

df.loc[df.groupby('id')['date'].idxmax()].reset_index(drop=T‌​rue)

输出:

    id                date remarks
2   1 2015-01-13 12:00:15  Not Ok
3   2 2015-01-14 01:00:15     Bad
4   3 2015-01-15 01:00:15    Good

如果你不想索引并打算用新索引创建一个新的数据框,那么(谢谢@Zero)

this.httpClient.post(url, body)
  .timeout(10000)
  .retryWhen(error => {
    return error.delay(500).take(5);
  })
.subscribe(
  response => {
    // stuff
  },
  error => {
    // stuff
  }