pandas 只保留日期,使用pandas.to_datetime时,只保留日期部分

博客探讨了如何利用Pandas的`.dt`属性快速将日期列转换为日期类型,从而在CSV输出时不包含时间部分。自Pandas 0.15.0版本起,可以简单地通过`df['just_date'] = df['dates'].dt.date`来实现整个列的类型转换,提高了处理大量数据的效率。
摘要由CSDN通过智能技术生成

I am using pandas.to_datetime to parse the dates in my data. Pandas by default represent the dates with datetime64[ns] even though the dates are all daily only.

I wonder whether there is an elegant/clever way to convert the dates to datetime.date or datetime64[D] so that when I write the data to csv, the dates are not appended with 00:00:00. I know I can convert the type manually element-by-element:

[dt.to_datetime().date() for dt in df.dates]

But this is really slow since I have many rows and it sort of defeats the purpose of using pandas.to_datetime. Is there a way to convert the dtype of the entire column at once? Or alternatively, does pandas.to_datetime support a precision specification so that I can get rid of the time part while working with daily data?

解决方案

Since version 0.15.0 this can now be easily done using .dt to access just the date component:

df['just_date'] = df['dates'].dt.date

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值