Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop the year from "Year-month-date" format in a pandas dataframe

I have a Pandas dataframe with many columns. The first column has dates listed as "Year-Month-Date" already set as a datetime type by using:

df_all['Date']=pd.to_datetime(df_all['Date'].astype(str),errors='coerce')

The data looks like:

0     2008-01-01 00:00:00   100   16250.0
1     2008-01-01 00:00:00   150   13740.0
2     2008-01-01 00:00:00   200   11900.0
3     2008-01-01 00:00:00   250   10460.0

I wish to simply drop the year so the column reads "Month-Date" without changing the other data in the columns associated with each row.

like image 427
Jonathon Avatar asked Sep 03 '25 03:09

Jonathon


1 Answers

If df_all['Date'] is string datatype, then you can use the str accessor with slicing like this:

df['Date'] = df_all['Date'].str[5:]

However, if df_all['Date'] is a datetime dtype then you can the date accessor with strfttime:

df_all['Date'] = df_all['Date'].dt.strftime('%m-%d %H:%M:%S')

Output:

             Date    A        B
0  01-01 00:00:00  100  16250.0
1  01-01 00:00:00  150  13740.0
2  01-01 00:00:00  200  11900.0
3  01-01 00:00:00  250  10460.0
like image 89
Scott Boston Avatar answered Sep 06 '25 03:09

Scott Boston