Python 在熊猫数据框中找到最近的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29886609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:08:09  来源:igfitidea点击:

find most recent date in pandas dataframe

pythonpandas

提问by Sarah Connors

I have a csv file, that I read into a pandas dataframe. The date and times are listed in a column "DateTime". I want to find the most recent and the least recent date to create an index to create a time series graph. Does pandas have a function that will return the most recent and the least recent date?

我有一个 csv 文件,我读入了一个熊猫数据框。日期和时间列在“DateTime”列中。我想找到最近和最近的日期来创建索引来创建时间序列图。Pandas 有返回最近和最近日期的函数吗?

Edit:
I already tried using min and max. They give incorrect answers.

编辑:
我已经尝试使用最小值和最大值。他们给出了错误的答案。

>>> f['Start Date']  
Trip ID  
4576       8/29/2013 14:13  
4607       8/29/2013 14:42  
4130       8/29/2013 10:16  
4251       8/29/2013 11:29  
4299       8/29/2013 12:02  
4927       8/29/2013 18:54  
4500       8/29/2013 13:25  
4563       8/29/2013 14:02  
4760       8/29/2013 17:01  
4258       8/29/2013 11:33  
4549       8/29/2013 13:52  
4498       8/29/2013 13:23  
4965       8/29/2013 19:32  
4557       8/29/2013 13:57  
4386       8/29/2013 12:31  
...  
198757     2/28/2014 20:40  
198760     2/28/2014 20:59  
198761     2/28/2014 20:59  
198763     2/28/2014 21:32  
198764     2/28/2014 21:32  
198765     2/28/2014 21:34  
198766     2/28/2014 21:41  
198767     2/28/2014 21:50  
198768     2/28/2014 21:54  
198770     2/28/2014 22:19  
198771     2/28/2014 22:15  
198772     2/28/2014 22:38  
198773     2/28/2014 22:45  
198774     2/28/2014 23:01  
198775     2/28/2014 23:20  
Name: Start Date, Length: 144015, dtype: object  
>>> min(f['Start Date'])  
'1/1/2014 0:14'  
>>> max(f['Start Date'])  
'9/9/2013 9:59'  

回答by Kathirmani Sukumar

First convert your date column in to a datetime column using

首先使用将日期列转换为日期时间列

>> df['StartDate'] = pd.to_datetime(df['StartDate'])
>> least_recent_date = df['StartDate'].min()
>> recent_date = df['StartDate'].max()