首页 > 解决方案 > 如何在pandas中将日期列转换为日期、月份和年份格式的三列?

问题描述

我想将给定的日期列转换为日期、月份和年份格式。最初,转换后有 2 列,它将是 4 列

Country|Date|Month|Year

给定的数据框的类型

test=pd.DataFrame({'Date':['2014,1,1','2014,4,17'],'Country':['Denmark','Australia']})

标签: python-3.xpandas

解决方案


熊猫有一个to_datetime功能。

import pandas as pd
df = pd.DataFrame({'Date':['2014,1,1','2014,4,17']})
df["Date"] = pd.to_datetime(df["Date"], format="%Y,%m,%d")

# If you want to save other datetime attributes as their own columns
# just pull them out assign them to their own columns
# df["Month"] = df["Date"].dt.month 
# df["Year"] = df["Date"].dt.year

推荐阅读