11

I have a DataFrame with time index like:

df.index = [2013-09-09 06:23:18, 2013-09-10 07:09:05, ..., 2014-02-02 06:04:04]

How could I choose rows in certain weekday, like Monday? Then I won't have the rows in other weekdays. Any help appreciated.

user3271033
  • 121
  • 3
  • 8

2 Answers2

15

You can get the weekday by df.index.weekday, note that Monday = 0 and Sunday = 6

To select the rows on Monday, you can do

df = df[df.index.weekday==0]
jpp
  • 159,742
  • 34
  • 281
  • 339
waitingkuo
  • 89,478
  • 28
  • 112
  • 118
2

Here "Date" is the column name. Creating new column "weekday"

df["weekday"] = pd.to_datetime(df.Date).dt.dayofweek

From this column you can select any weekday from dataframe

df.loc[df["weekday"] ==6]

Here 6 denotes "Sunday"

Sven Hakvoort
  • 3,543
  • 2
  • 17
  • 34
  • 2
    This is not correct, according to [the documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.dayofweek.html), `dayofweek` (as well as `weekday`) returns "the day of the week with Monday=0, Sunday=6"! – filaton Apr 26 '20 at 16:15