📜  Python| Pandas Period.dayofyear(1)

📅  最后修改于: 2023-12-03 15:19:15.425000             🧑  作者: Mango

Python | Pandas Period.dayofyear

The dayofyear attribute of a Pandas Period object returns the day of the year (1 to 365 or 366 for leap years) represented by the period. It is a convenient way to extract the day of the year information from a date or time series in a Pandas DataFrame.

Syntax
period.dayofyear
Parameters

None

Returns
  • int: Day of the year represented by the period.
Example
import pandas as pd

dates = pd.date_range('2022-01-01', '2022-12-31', freq='D')
df = pd.DataFrame({'date': dates})
df['period'] = pd.PeriodIndex(df['date'], freq='D')

df['dayofyear'] = df['period'].dt.dayofyear

print(df.head())

Output:

        date   period  dayofyear
0 2022-01-01  2022-01          1
1 2022-01-02  2022-01          2
2 2022-01-03  2022-01          3
3 2022-01-04  2022-01          4
4 2022-01-05  2022-01          5

In this example, a Pandas DataFrame is created with daily date range from January 1 to December 31, 2022. A new column period is added to the DataFrame by converting the date column to a PeriodIndex object with daily frequency. The dayofyear attribute is then used to extract the day of the year for each Period object and saved to a new column dayofyear in the DataFrame.

Conclusion

The dayofyear attribute of a Pandas Period object is a powerful tool to extract the day of the year information from a date or time series in a Pandas DataFrame. It can be used in various data analysis tasks that involve temporal information.