【问题标题】:How to convert date column to into three columns of date, month and year format in pandas?如何在pandas中将日期列转换为日期、月份和年份格式的三列?
【发布时间】:2018-12-29 07:17:28
【问题描述】:

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

Country|Date|Month|Year

给定的数据框的类型

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

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    Pandas 有一个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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多