[英]Pandas: Find index of max string value in a column
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. 我注意到argmax和idmax不适用于字符串。 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' 返回:'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' 返回:ValueError:无法将字符串转换为float:'2017-01-26 16:33:16'
If dont want converting to datetime
, you can use boolean indexing
with comparing column with max
value: 如果不想转换为datetime
,则可以将boolean indexing
与具有max
列进行比较:
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]
Source DF: 来源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: 解决方案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: 解决方案2:
In [62]: df.loc[pd.to_datetime(df['Start_time']).idxmax()]
Out[62]:
Start_time 2017-05-02 15:47:21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.