Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
recategorized by

I have the date column of a format YYYY-MM-DD. I want to slice only my year and month from it. But I don't want this "-" as I have to later convert it to an integer to feed it to the linear regression model. Its data type is "object".

This is my Dataframe:-

         date   open  close   high    low

0  2019-10-08  56.46  56.10  57.02  56.08

1  2019-10-09  56.76  56.76  56.95  56.41

2  2019-10-10  56.98  57.52  57.61  56.83

3  2019-10-11  58.24  59.05  59.41  58.08

4  2019-10-14  58.73  58.97  59.53  58.67

1 Answer

0 votes
by (36.8k points)

You can use the pd.to_datetime to convert the date column to datetime then use the pd.Series.dt.strftime.

s = pd.to_datetime(df['date'])

df['date'] = s.dt.strftime("%Y%m") # would give 202010

# or

# df['date'] = s.dt.strftime("%y%m") # would give 2010

 If you are a beginner and want to know more about Data Science the do check out the Data Science course

Related questions

Browse Categories

...