How to filter one date column by weeks?
Question:
There is a problem – I created a table with dates for couple of years, and now i need to filter it by weeks (to work only with with first days of every week), but no matter how i try it doesn’t work. Will be glad if you’ll help me.
df1 = pd.DataFrame({"Date":pd.date_range(start='1/1/2018', end='31/12/2019')})
weeks = pd.date_range(df1['Date'].min(), df1['Date'].max(), freq ='W')
df1[weeks]
I could convert it into pd.DataFrame but then it won’t give an error but instead it gives NaT in all rows.
Answers:
You can do it easily just by selecting all the Mondays:
df1[lambda x: x["Date"].dt.day_name() == "Monday"]
Date
0 2018-01-01
7 2018-01-08
14 2018-01-15
21 2018-01-22
28 2018-01-29
.. ...
700 2019-12-02
707 2019-12-09
714 2019-12-16
721 2019-12-23
728 2019-12-30
You can use the dt
accessor and dayofweek
:
# 6 -> Sunday, 0 -> Monday
>>> df1[df1['Date'].dt.dayofweek == 0]
Date
0 2018-01-01
7 2018-01-08
14 2018-01-15
21 2018-01-22
28 2018-01-29
.. ...
700 2019-12-02
707 2019-12-09
714 2019-12-16
721 2019-12-23
728 2019-12-30
[105 rows x 1 columns]
There is a problem – I created a table with dates for couple of years, and now i need to filter it by weeks (to work only with with first days of every week), but no matter how i try it doesn’t work. Will be glad if you’ll help me.
df1 = pd.DataFrame({"Date":pd.date_range(start='1/1/2018', end='31/12/2019')})
weeks = pd.date_range(df1['Date'].min(), df1['Date'].max(), freq ='W')
df1[weeks]
I could convert it into pd.DataFrame but then it won’t give an error but instead it gives NaT in all rows.
You can do it easily just by selecting all the Mondays:
df1[lambda x: x["Date"].dt.day_name() == "Monday"]
Date
0 2018-01-01
7 2018-01-08
14 2018-01-15
21 2018-01-22
28 2018-01-29
.. ...
700 2019-12-02
707 2019-12-09
714 2019-12-16
721 2019-12-23
728 2019-12-30
You can use the dt
accessor and dayofweek
:
# 6 -> Sunday, 0 -> Monday
>>> df1[df1['Date'].dt.dayofweek == 0]
Date
0 2018-01-01
7 2018-01-08
14 2018-01-15
21 2018-01-22
28 2018-01-29
.. ...
700 2019-12-02
707 2019-12-09
714 2019-12-16
721 2019-12-23
728 2019-12-30
[105 rows x 1 columns]