如何将日期列转换为大熊猫中日期,月份和年份格式的三列?

时间:2018-07-20 23:56:03

标签: python-3.x pandas

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

一样是4列
Country|Date|Month|Year

给定的数据帧是类型

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

1 个答案:

答案 0 :(得分:2)

熊猫具有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