Given the following dataframe:
| ID | date |
|---------------------|--------------------------------|
| 1 | 2022-02-03 22:01:12+01:00 |
| 2 | 2022-02-04 21:11:21+01:00 |
| 3 | 2022-02-05 11:11:21+01:00 |
| 4 | 2022-02-07 23:01:12+01:00 |
| 5 | 2022-02-07 14:31:14+02:00 |
| 6 | 2022-02-08 18:12:01+02:00 |
| 7 | 2022-02-09 20:21:02+02:00 |
| 8 | 2022-02-11 15:41:25+02:00 |
| 9 | 2022-02-15 11:21:27+02:00 |
I would like to optimise the code of the following function:
Returns all rows whose date (YYYY-MM-DD) matches the date passed by parameter.
# Function to search by exact %Y-%m-%d date
def select_exact_date(df, date):
date = pd.to_datetime(date, format='%Y-%m-%d %H:%M:%S')
date_dt = date.date()
# Create a copy of the original df
subset = df.copy()
# Creates a temporary column to store the values related to the specific date
subset['tmp_date'] = subset['date'].apply(lambda a: a.date())
mask = (subset['tmp_date'] == date_dt)
df = df.loc[mask]
return df
Result:
select_exact_date(df, '2022-02-07')
#Output
| ID | date |
|---------------------|--------------------------------|
| 4 | 2022-02-07 23:01:12+01:00 |
| 5 | 2022-02-07 14:31:14+02:00 |
I hope you can help me. Thank you in advance.
date
string parameter actually come from? I ask because if it's far-removed from user input or file content, it should have been converted to a datetime object earlier than where you show it. \$\endgroup\$input()
five functions ago? Read from a file into a different dataframe? Etc. \$\endgroup\$