Reputation: 11460
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'
Upvotes: 3
Views: 7580
Reputation: 210862
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
Upvotes: 4
Reputation: 862841
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]
Upvotes: 4