Python Pandas. Date object split by separate columns.

前端 未结 2 1556
长发绾君心
长发绾君心 2021-01-29 11:02

I have dates in Python (pandas) written as \"1/31/2010\". To apply linear regression I want to have 3 separate variables: number of day, number of month, number of year.

2条回答
  •  無奈伤痛
    2021-01-29 11:39

    df['date'] = pd.to_datetime(df['date'])
    
    #Create 3 additional columns
    df['day'] = df['date'].dt.day
    df['month'] = df['date'].dt.month
    df['year'] = df['date'].dt.year
    

    Ideally, you can do this without having to create 3 additional columns, you can just pass the Series to your function.

    In [2]: pd.to_datetime('01/31/2010').day
    Out[2]: 31
    
    In [3]: pd.to_datetime('01/31/2010').month
    Out[3]: 1
    
    In [4]: pd.to_datetime('01/31/2010').year
    Out[4]: 2010
    

提交回复
热议问题