2

I have a pandas DataFrame looking like this:

date      info          
A         x
A         y 
B         z
B         x
C         y

I only want to know the last date. In this case it is C.

I thought that I can get this by grouping and sorting by the Date column:

 df.groupby('date', sort=True)

... and then accessing the last group. However, there is no way of accessing the last group as one-liner? Is there a better way to do this?

2 Answers 2

2

I think I was just over-complicating things. to get C this should be enough:

df['date'].max()
1

If you just want to get the date as a value, your own answer is fine. But if you want to get the actual record with biggest date, you can use head():

In [4]: df.sort('date', ascending=False).head(1)
Out[4]: 
  date info
4    C    y

You can also use ascending parameter to sort by other columns.

In [4]: df.sort(columns=['date', 'info'], ascending=[False, True]).head(1)
Out[4]: 
  date info
4    C    y
6
  • 1
    You want tail for the last rows
    – EdChum
    May 15, 2015 at 9:44
  • well I ordered desc by date, so head will work :) But you're right, tail could be more descriptive. I always translate the task to SQL in my head, and in SQL there's only top n keyword. May 15, 2015 at 9:58
  • @EdChum BTW do you know if it's possible to do partial sort in pandas? For example, in this case we don't want to sort the whole dataframe, we just want to take k largest. So if we could do partial heapsort on the dataframe it would be nice May 15, 2015 at 10:08
  • Not off the top of my head you'd have to write your own code I think, sort does support kind='heapsort' as a sort type, there is a similar bit of code here: github.com/pydata/pandas/issues/2995 which may lead you to an answer
    – EdChum
    May 15, 2015 at 10:13
  • 1
    Thanks, also just found this one, could be useful, but still requires some wrapper code at the least - berkeleyanalytics.com/bottleneck/… May 15, 2015 at 10:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.