Skip to content Skip to sidebar Skip to footer

How To Split A Date Column Into Separate Day , Month ,year Column In Pandas

I have a dataset df: Dewptm Fog Humidity Pressurem Tempm Wspdm Rainfall datetime_utc 1996-11-01 11.666667 0.0 52.91666

Solution 1:

The problem is that datetime_utc is in your index instead a column, so you have to access your index to be able to make your new columns:

df['day']=df.index.daydf['month']=df.index.monthdf['year']=df.index.yearprint(df)DewptmFogHumidityPressuremTempmWspdm\datetime_utc1996-11-01    11.6666670.052.916667-2659.66666722.3333332.4666671996-11-02    10.4583330.048.6250001009.833333  22.9166678.0285711996-11-03    12.0416670.055.9583331010.500000  21.7916674.8045451996-11-04    10.2222220.048.0555561011.333333  22.7222221.964706Rainfalldaymonthyeardatetime_utc1996-11-01           011119961996-11-02           021119961996-11-03           031119961996-11-04           04111996

If you want datetime_utc as a column you have to reset your index and then you can access the datetime methods with dt.month, dt.year and dt.day like following:

# Reset our index so datetime_utc becomes a column
df.reset_index(inplace=True)

# Create new columnsdf['day'] = df['datetime_utc'].dt.day
df['month'] = df['datetime_utc'].dt.month
df['year'] = df['datetime_utc'].dt.year

print(df)
  datetime_utc     Dewptm  Fog   Humidity    Pressurem      Tempm     Wspdm  \
0   1996-11-01  11.666667  0.0  52.916667 -2659.666667  22.333333  2.466667   
1   1996-11-02  10.458333  0.0  48.625000  1009.833333  22.916667  8.028571   
2   1996-11-03  12.041667  0.0  55.958333  1010.500000  21.791667  4.804545   
3   1996-11-04  10.222222  0.0  48.055556  1011.333333  22.722222  1.964706   

   Rainfall  day  month  year  
0         0    1     11  1996  
1         0    2     11  1996  
2         0    3     11  1996  
3         0    4     11  1996  

Note if your index is not in datetime type yet, use the following before you try to extract year, month and day:

df.index = pd.to_datetime(df.index)

Post a Comment for "How To Split A Date Column Into Separate Day , Month ,year Column In Pandas"