How to filter only the first Friday in a column with one week of data (Pandas)

Viewed 83

I have a column that contains Friday-Friday dates ex. Fri March 4 to Fri March 11. I only want to filter the earliest Friday date. Any suggestions. I figured a way to sort out the min value, but I feel like there's a better method

df['Submitted On'] = pd.to_datetime(df['Submitted On'])
early = df['Submitted On'].min()
df = df.loc[df['Submitted On'] != early]
1 Answers

Although I don't know the use case for your data, your method is a little brittle. If for some reason the range of dates in your column changes, then you're filtering out the earliest date regardless of whether it's a Friday or not.

You can use the .dt.dayofweek method for Series which will return integers 0 through 6 for the day of the week meaning Friday is 4, and filter based on the first occurrence of a Friday. For example:

df = pd.DataFrame({'Submitted On': pd.date_range('2022-03-04','2022-03-11'), 'value':range(8)})
df['Submitted On'] = pd.to_datetime(df['Submitted On'])
filtered_df = df.drop(labels=df[df['Submitted On'].dt.dayofweek == 4].index.values[0])

Result:

  Submitted On  value
1   2022-03-05      1
2   2022-03-06      2
3   2022-03-07      3
4   2022-03-08      4
5   2022-03-09      5
6   2022-03-10      6
7   2022-03-11      7

And note that if I change the date range slightly, it still drops the first Friday:

df = pd.DataFrame({'Submitted On': pd.date_range('2022-03-03','2022-03-12'), 'value':range(10)})
filtered_df = df.drop(labels=df[df['Submitted On'].dt.dayofweek == 4].index.values[0])

Result:

  Submitted On  value
0   2022-03-03      0
2   2022-03-05      2
3   2022-03-06      3
4   2022-03-07      4
5   2022-03-08      5
6   2022-03-09      6
7   2022-03-10      7
8   2022-03-11      8
9   2022-03-12      9
Related