在pandas数据框中查找最近的日期

35

我有一个csv文件,将其读入pandas dataframe中。日期和时间在“DateTime”列中列出。我想找到最近和最早的日期以创建索引来创建时间序列图表。Pandas是否有函数可以返回最近和最早的日期?

编辑:
我已经尝试使用min和max。它们给出了错误的答案。

>>> 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'  

你可以在 Pandas Series 上使用 Python 的 minmax 函数,这样就能得到你想要的结果。 - Haleemur Ali
如果您正在寻找图形功能,您也可以查看http://pandas.pydata.org/pandas-docs/dev/timeseries.html。 - Yantraguru
1个回答

72

首先使用以下方法将您的日期列转换为日期时间列:

>> df['StartDate'] = pd.to_datetime(df['StartDate'])

然后,您可以使用以下方法找到最早日期和最近日期:

>> least_recent_date = df['StartDate'].min()
>> most_recent_date = df['StartDate'].max()

有没有一种简单的方法来检查列以找出它是什么类或类型,以确定是否需要更改变量类型?(另外,非常感谢) - Sarah Connors
1
使用df['StartDate'].dtype来获取列的类型 - Kathirmani Sukumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接