gpt4 book ai didi

time-series - 如何更改数据框列中的日期格式。

转载 作者:太空宇宙 更新时间:2023-11-04 05:41:30 25 4
gpt4 key购买 nike

我在 DataFrame 中有一个日期格式为 yyyymmdd 的列,我需要将其永久更改为 yyyy-mm-dd。

我该怎么做?

最佳答案

鉴于您在评论中提供的信息,列值不能采用 yyyy-mm-dd 的形式因为列 dtype 是 int64 .

您可以将列 dtype 更改为 str , 但数据不会有用(即你将无法对其进行任何日期计算,虽然 <> 应该仍然有效,但按字典顺序排列)。如果这仍然是您想要的并假设 df是数据框,日期列名称是 date :

def format_date_col(x):
x = str(x)
return '-'.join([x[:4], x[4:6], x[6:]])

# or maybe like that for better readability:
x = str(x)
return '{year}-{month}-{day}'.format(year=x[:4], month=x[4:6], day=x[6:])

df['date'] = df['date'].apply(format_date_col)

更好的方法是使用实​​际日期数据类型:

from datetime import datetime 

def format_date_col(x):
return datetime.strptime(str(x), '%Y%m%d')

df['date'] = df['date'].apply(format_date_col)

print df['date'].dtype
>> datetime64[ns]

关于time-series - 如何更改数据框列中的日期格式。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33775313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com