I have the following DF
JavaScript
x
6
1
45 2018-01-01
2
73 2018-02-08
3
74 2018-02-08
4
75 2018-02-08
5
76 2018-02-08
6
I want to extract the month name and year in a simple way in the following format:
JavaScript
1
6
1
45 Jan-2018
2
73 Feb-2018
3
74 Feb-2018
4
75 Feb-2018
5
76 Feb-2018
6
I have used the df.Date.dt.to_period("M")
which return "2018-01"
format.
Advertisement
Answer
Cast you date from object to actual datetime and use dt to access what you need.
JavaScript
1
13
13
1
import pandas as pd
2
3
df = pd.DataFrame({'Date':['2019-01-01','2019-02-08']})
4
5
df['Date'] = pd.to_datetime(df['Date'])
6
7
# You can format your date as you wish
8
df['Mon_Year'] = df['Date'].dt.strftime('%b-%Y')
9
10
# the result is object/string unlike `.dt.to_period('M')` that retains datetime data type.
11
12
print(df['Mon_Year'])
13
Visual Format without affecting data types
We could also work with style to get the visual in the way we want without messing with underlying types
JavaScript
1
3
1
# note: returns a style object not df
2
df.style.format({"Date": lambda t: t.strftime("%b-%Y")})
3