How to check if pandas DateTimeIndex dates belong to a list?
Last Updated :
02 Dec, 2024
To check if Pandas DateTimeIndex dates belong to a list, we can use the isin()
method. In this we basically consider a subset of dates and check whether those dates are present in the list or not.
Check whether the set of dates exist in date column or not
isin() is a method in Pandas that is used to check whether the element belongs to that particular series or list. This is a useful function as it helps to filter out the elements. If the element is present in that Series, it returns True else it returns False. This is useful for filtering out the dates from the given Series.
Here we will consider an example where we generate dataframe that comprises of dates using date_range and define a list of dates to check whether those exist in the dataframe or not using isin().
Python
import pandas as pd
# Create a DataFrame with a DateTimeIndex for one week
date_range = pd.date_range(start='2024-12-20', periods=7, freq='D')
df = pd.DataFrame({"temperature": [12, 14, 15, 13, 11, 10, 9]}, index=date_range)
# Define a list of holidays
holidays = ['2024-12-22', '2024-12-25']
# Convert holidays to datetime format
holidays = pd.to_datetime(holidays)
# Check if dates in the index belong to the list of holidays
df['is_holiday'] = df.index.isin(holidays)
print(df)
Output:
checking if pandas DateTimeIndex dates belong to a listFrom the output we can see that we are filtering those dates that are present and setting the values to True. For those dates that do not exist in the list, we set them to False.
Check if the dates belong to that particular list
Intersection is basically finding the common elements between two lists. In Dataframe we can use intersection to check whether the dates belong to that Series or not. Let us assume that we have a dataframe that comprises of dates and associated values. We specify a list of dates and using intersection we check if that date is member or not. Finally we use isin() to set the status as True or False.
Python
import pandas as pd
# Create a DataFrame with a DateTimeIndex
date_range = pd.date_range(start='2024-12-01', periods=7, freq='D')
df = pd.DataFrame({"value": range(10, 80, 10)}, index=date_range)
# Define a list of dates to check
dates_to_check = pd.to_datetime(['2024-12-02', '2024-12-05', '2024-12-07'])
# Find the intersection of dates
common_dates = df.index.intersection(dates_to_check)
# Add a column to indicate whether each date is in the list
df['is_in_list'] = df.index.isin(common_dates)
print(df)
Output value is_in_list
2024-12-01 10 False
2024-12-02 20 True
2024-12-03 30 False
2024-12-04 40 False
2024-12-05 50 True
2024-12-06 60 ...
Using lambda and map
Lambda is an anonymous function that returns the values when certain condition is satisfied. Now using the map we assign boolean values. Let us consider a sample example in which we have dataframe and some other columns. We have a list of dates which we convert to date time series. Using Lambda function we check that the dates exist in that list or not and using map we assign True to those dates that exists.
Python
import pandas as pd
# Create a DataFrame with a DateTimeIndex
date_range = pd.date_range(start='2024-11-20', periods=7, freq='D')
df = pd.DataFrame({"temperature": [13, 24, 15, 13, 11, 10, 9]}, index=date_range)
# Define a list of holidays and convert to datetime
li = pd.to_datetime(['2024-11-22', '2024-11-25'])
# Use a lambda function to check if each date belongs to the list
df['is_in_list'] = df.index.map(lambda date: date in li)
print(df)
Output:
lambda and map to check the membershipUsing List Comprehension to filter out the dates
List Comprehension is an effective technique that is used to filter out the values based on any particular condition. Here we generate dates for the dataframe. These dates also act as indices for the dataframe which is used for comparison and it returns True or False accordingly.
Python
import pandas as pd
# Create a DataFrame with a DateTimeIndex for a week
date_range = pd.date_range(start='2024-11-15', periods=7, freq='D')
df = pd.DataFrame({"sales": [100, 150, 200, 130, 170, 120, 180]}, index=date_range)
# Define a list of dates to check
dates_to_check = pd.to_datetime(['2024-11-16', '2024-11-19', '2024-11-20'])
# Use list comprehension to create a boolean array
df['is_in_list'] = [date in dates_to_check for date in df.index]
# Print the resulting DataFrame
print(df)
Output sales is_in_list
2024-11-15 100 False
2024-11-16 150 True
2024-11-17 200 False
2024-11-18 130 False
2024-11-19 170 True
2024-11-20 120 ...
Comparison of Techniques for Filtering DateTimeIndex dates
Name | Advantage | Disadvantage |
---|
.isin() | Simple and fast | Slow and if the dates are not in appropriate format it can leads to error |
---|
intersection | Efficient for large data | Does not consider the duplicates |
---|
lambda | Useful for small datasets | Slower and performs elements wise comparison |
---|
List Comprehension | Useful for small datasets | Iterating over the large dataset consumes much time and resources. |
---|
Similar Reads
How to Convert Datetime to Date in Pandas ? DateTime is a collection of dates and times in the format of "yyyy-mm-dd HH:MM:SS" where yyyy-mm-dd is referred to as the date and HH:MM:SS is referred to as Time. In this article, we are going to discuss converting DateTime to date in pandas. For that, we will extract the only date from DateTime us
4 min read
How to Convert Integer to Datetime in Pandas DataFrame? Let's discuss how to convert an Integer to Datetime in it. Now to convert Integers to Datetime in Pandas DataFrame. Syntax of  pd.to_datetimedf['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)Create the DataFrame to Convert Integer to Datetime in Pandas Check
2 min read
How to Change Pandas Dataframe Datetime to Time The DatetimeIndex contains datetime64[ns] data type, which represents timestamps with nanosecond precision. In many cases, we may just want to extract the time component from a Pandas Datetime column or index. Let's discuss easy ways to convert the Datetime to Time data while preserving all the time
2 min read
How to Convert Float to Datetime in Pandas DataFrame? Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax:
3 min read
Python | Pandas DatetimeIndex.date Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.date attribute outputs an Index object containing the date values
2 min read
Python | Pandas DatetimeIndex.to_frame() Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.to_frame() function create a DataFrame with a column containing t
2 min read