Python | Pandas PeriodIndex.daysinmonth

Python | Pandas PeriodIndex.daysinmonth

The daysinmonth attribute of a Pandas PeriodIndex object returns the number of days in the month of each period in the PeriodIndex. It can be useful when you want to know how many days are in the month for each period in a given time series.

Here's how you can use the daysinmonth attribute:

import pandas as pd # Creating a PeriodIndex for some specific months pi = pd.PeriodIndex(['2021-01', '2021-02', '2021-03', '2021-04'], freq='M') # 'M' stands for monthly frequency # Get the number of days in the month for each period print(pi.daysinmonth) 

Output:

[31 28 31 30] 

The output corresponds to the number of days in January, February, March, and April of 2021 respectively.

If you're working within a DataFrame context, you can use this attribute to generate a new column:

import pandas as pd # Sample dataframe with periods df = pd.DataFrame({ 'periods': ['2021-01', '2021-02', '2021-03', '2021-04'] }) # Convert the 'periods' column to PeriodIndex df['periods'] = pd.PeriodIndex(df['periods'], freq='M') # Create a new column with the number of days in the month df['days_in_month'] = df['periods'].daysinmonth print(df) 

Output:

 periods days_in_month 0 2021-01 31 1 2021-02 28 2 2021-03 31 3 2021-04 30 

Now, the days_in_month column in the DataFrame contains the number of days in each month for the periods specified in the periods column.


More Tags

criteriaquery spring-social-facebook excel-2007 appfuse coldfusion heatmap tabular performance-testing bounds alembic

More Programming Guides

Other Guides

More Programming Examples