2

Given Timestamp indices with many per day, how can I get a list containing only the last Timestamp of a day? So in case I have such:

import pandas as pd

all   = [pd.Timestamp('2016-05-01 10:23:45'), 
         pd.Timestamp('2016-05-01 18:56:34'), 
         pd.Timestamp('2016-05-01 23:56:37'),
         pd.Timestamp('2016-05-02 03:54:24'), 
         pd.Timestamp('2016-05-02 14:32:45'), 
         pd.Timestamp('2016-05-02 15:38:55')]

I would like to get:

# End of Day:
EoD   = [pd.Timestamp('2016-05-01 23:56:37'), 
         pd.Timestamp('2016-05-02 15:38:55')]

Thx in advance!

2
  • 1
    are you working with Vanilla Python lists or with Pandas structures? Commented Apr 26, 2017 at 21:14
  • Sry, I should have been more clear. I extract those from a Pandas Dataframe (with DatetimeIndex index) Commented Apr 26, 2017 at 22:48

2 Answers 2

3

Try pandas groupby

all   = pd.Series(all)
all.groupby([all.dt.year, all.dt.month, all.dt.day]).max()

You get

2016  5  1   2016-05-01 23:56:37
         2   2016-05-02 15:38:55
Sign up to request clarification or add additional context in comments.

1 Comment

That is nice, but I wasn't precise enough. Actually, I use a Dataframe with a DatetimeIndex. Your way works when I retrieve the index first and proceed as proposed. However, is there a more direct way from the Dataframe itself?
0

I've created an example dataframe.

import pandas as pd
all   = [pd.Timestamp('2016-05-01 10:23:45'), 
         pd.Timestamp('2016-05-01 18:56:34'), 
         pd.Timestamp('2016-05-01 23:56:37'),
         pd.Timestamp('2016-05-02 03:54:24'), 
         pd.Timestamp('2016-05-02 14:32:45'), 
         pd.Timestamp('2016-05-02 15:38:55')]
df = pd.DataFrame({'values':0}, index = all)

Assuming your data frame is structured as example, most importantly is sorted by index, code below is supposed to help you.

for date in set(df.index.date):
    print(df[df.index.date == date].iloc[-1,:])

This code will for each unique date in your dataframe return last row of the slice so while sorted it'll return your last record for the day. And hey, it's pythonic. (I believe so at least)

1 Comment

Thx, interesting approach. However, I think for this, you'd still need to sort the output and it doesn't scale as nicely as the other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.