pandas: Extracting only the month-day values for rows from a column

Viewed 70

I want to plot a line graph for my data however the x-axis becomes extremely tight together due to the long date format (Y-M-D), and I've checked the data type for 'date' and it returned:

In[200]: df['date'].dtypes
Out[200]: dtype('O')

So my 'date' values are:

date
----
2020-04-12
2020-05-13
2020-02-02

but I want to extract only the month and day to make the column look like

date
----
04-12
05-13
02-02

How should I do this? I apologise for dupes as I couldn't find anything similar due to my datatype being 'O'. Appreciate all the help!

1 Answers

Use Series.str.split and select second ist by indexing str[1]:

df['date'] = df['date'].str.split('-', n=1).str[1]
#if dates objects
#df['date'] = df['date'].astype(str).str.split('-', n=1).str[1]
print (df)
    date
0  04-12
1  05-13
2  02-02

Or convert to datetimes by to_datetime with Series.dt.strftime:

df['date'] = pd.to_datetime(df['date']).dt.strftime('%m-%d')
Related