Pandas How To Uncategorized How to find the first day of the month in Pandas

How to find the first day of the month in Pandas

In Pandas, you can find the first day of the month from a given date by using the to_period method and passing in ‘M’ as the frequency argument.

For example, consider the following date:

import pandas as pd
date = pd.to_datetime("2022-02-15")

You can find the first day of the month for the given date by converting it to a Period object:

first_day_of_month = date.to_period("M").start_time

The resulting first_day_of_month will be the first day of the month of the given date:

Timestamp('2022-02-01 00:00:00')

If you have a column in a DataFrame with dates, you can apply the same logic to all values in the column to find the first day of the month for each date. For example:

import pandas as pd
df = pd.DataFrame({"date": [pd.to_datetime("2022-02-15"),
pd.to_datetime("2021-01-31")]})
df["first_day_of_month"] = df["date"].dt.to_period("M").dt.start_time

The resulting DataFrame will have an additional column first_day_of_month with the first day of the month for each date in the date column:

date first_day_of_month
0 2022-02-15 2022-02-01
1 2021-01-31 2021-01-01

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post