将 float64 列转换为日期时间 pandas [英] Convert float64 column to datetime pandas
本文介绍了将 float64 列转换为日期时间 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 pandas DataFrame
列 dfA['TradeDate']
:
0 20100329.0
1 20100328.0
2 20100329.0
...
我希望将其转换为日期时间.
and I wish to transform it to a datetime.
基于 SO 上的另一个步骤,我首先将其转换为字符串,然后应用 strptime
函数.
Based on another tread on SO, I convert it first to a string and then apply the strptime
function.
dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')
但是这会返回我的格式不正确的错误(ValueError
).
However this returns the error that my format is incorrect (ValueError
).
我发现的一个问题是该列不能正确地用于字符串,而是用于对象.
An issue that I spotted is that the column is not properly to string, but to an object.
当我尝试时:
dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype(int).astype(str),'%Y%m%d')
它返回:必须是 Str 而不是系列.
It returns: must be a Str and not Series.
推荐答案
您可以使用:
df['TradeDate'] = pd.to_datetime(df['TradeDate'], format='%Y%m%d.0')
print (df)
TradeDate
0 2010-03-29
1 2010-03-28
2 2010-03-29
但是如果一些错误的值,添加 errors='coerce'
以替换它们到 NaT
But if some bad values, add errors='coerce'
for replace them to NaT
print (df)
TradeDate
0 20100329.0
1 20100328.0
2 20100329.0
3 20153030.0
4 yyy
df['TradeDate'] = pd.to_datetime(df['TradeDate'], format='%Y%m%d.0', errors='coerce')
print (df)
TradeDate
0 2010-03-29
1 2010-03-28
2 2010-03-29
3 NaT
4 NaT
这篇关于将 float64 列转换为日期时间 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文