3

I have some time values that are in string format. I would like to return the value of the most recent or "max" time in a column. I noticed that argmax and idmax don't work for strings. I would like to avoid converting them to find the index of the max value. Is there a way to return the index of the max string value?

df['Start_time'].max()

returns: '2017-05-02 15:47:21'

df.loc[df['Start_time'].idxmax()]

returns: ValueError: could not convert string to float: '2017-01-26 16:33:16'

2 Answers 2

4

If dont want converting to datetime, you can use boolean indexing with comparing column with max value:

print (df[df['Start_time'] == df['Start_time'].max()])

And for index is possible use:

df.index[df['Start_time'] == df['Start_time'].max()][0]

Or:

df[df['Start_time'] == df['Start_time'].max()].index[0] 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that works. This returns the index value only: df[df['Start_time'] == df['Start_time'].max()].index[0]
@sparrow - yes, exactly. I add it to answer with similar solution.
4

Source DF:

In [60]: df
Out[60]:
            Start_time
0  2017-05-01 16:16:16
1  2017-05-02 15:47:21
2  2017-05-01 10:10:10

Solution 1:

In [61]: df.iloc[df['Start_time'].values.argmax()]
Out[61]:
Start_time    2017-05-02 15:47:21
Name: 1, dtype: object

Solution 2:

In [62]: df.loc[pd.to_datetime(df['Start_time']).idxmax()]
Out[62]:
Start_time    2017-05-02 15:47:21

Comments

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.