How to fill a pandas column with a date range object?

Convert Date Range to column in Pandas

First, let’s create a DataFrame that we can work with. This DataFrame will represent basic employee information:

# Import the pandas library
import pandas as pd

# Create example employee data
employee_info = {'Emp_ID': [901, 910, 920],
                 'Employee_Name': ['Damian Ramirez', 'Jane Perez', 'Dorothy Gomez']}

employee_data = pd.DataFrame(employee_info)


# Create a range object
dates_rng = pd.date_range(start='2023-08-11', end='2023-08-13')

We will now add a column to our DataFrame for storing a range of dates. In this scenario, we will populate this column with dates spanning couple days.

# Create a range object
dates_rng = pd.date_range(start='2023-08-11', end='2023-08-13')

We then assign the date range object to each row in our data frame:

# Assigning the date range to each employee
employee_data['Work_Dates'] = [dates_rng] * len(employee_data)

At this point, each row in our DataFrame contains the entire date range. In order to assign one date to each row, we will expand the DataFrame. This creates a row that corresponds to an individual date for each employee.

# Expanding DataFrame to individual dates
employee_df = employee_data.explode('Work_Dates')

Here’s the DataFrame with the assigned date objects:

FAQ

How to create a date range excluding weekends?

  • Utilize pd.bdate_range instead of pd.date_range. Then define the start and end dates.Note that the pd.bdate_range function omits weekends by default.
  • Next, assign this business date range to the DataFrame.
  • Last, expand using the explode method, as shopwn in earlier steps.

Can I filter the DataFrame based on specific dates?

Definitely, apply DataFrame filtering techniques.
For example: you can use the.loc[] accessor or similar methods for conditional filtering of your DataFrame data.