在Pandas中如何将日期字符串的字符串转换为datetime对象并将它们放在DataFrame中? [英] In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?
本文介绍了在Pandas中如何将日期字符串的字符串转换为datetime对象并将它们放在DataFrame中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
date_stngs =('2008-12-20','2008-12-21','2008-12-22','2008- 12-23')
a = pd.Series(range(4),index =(range(4)))
为idx,日期为枚举(date_stngs):
a [idx] = pd.to_datetime(date)
此代码位产生错误: / p>
TypeError:'int'object is not iterable
任何人都可以告诉我如何将这一系列的日期时间字符串变成一个DataFrame作为 DateTime
对象?
解决方案
>>>将大熊猫导入为pd
>>> date_stngs =('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
>>> a = pd.Series([date_stngs中日期的[pd.to_datetime(date)])
>>> a
0 2008-12-20 00:00:00
1 2008-12-21 00:00:00
2 2008-12-22 00:00:00
3 2008-12-23 00:00:00
更新 p>
使用pandas.to_datetime(pd.Series(..))。它比上面的代码简明扼要。
>>> pd.to_datetime(pd.Series(date_stngs))
0 2008-12-20 00:00:00
1 2008-12-21 00:00:00
2 2008-12- 22 00:00:00
3 2008-12-23 00:00:00
import pandas as pd
date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
a = pd.Series(range(4),index = (range(4)))
for idx, date in enumerate(date_stngs):
a[idx]= pd.to_datetime(date)
This code bit produces error:
TypeError:" 'int' object is not iterable"
Can anyone tell me how to get this series of date time strings into a DataFrame as DateTime
objects?
解决方案
>>> import pandas as pd
>>> date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
>>> a = pd.Series([pd.to_datetime(date) for date in date_stngs])
>>> a
0 2008-12-20 00:00:00
1 2008-12-21 00:00:00
2 2008-12-22 00:00:00
3 2008-12-23 00:00:00
UPDATE
Use pandas.to_datetime(pd.Series(..)). It's concise and much faster than above code.
>>> pd.to_datetime(pd.Series(date_stngs))
0 2008-12-20 00:00:00
1 2008-12-21 00:00:00
2 2008-12-22 00:00:00
3 2008-12-23 00:00:00
这篇关于在Pandas中如何将日期字符串的字符串转换为datetime对象并将它们放在DataFrame中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文