Home > Net >  How to add day of the year column w.r.t Date in pandas
How to add day of the year column w.r.t Date in pandas

Time:09-20

I have a date column and I want to add the day of year(1-365), day of half year(1-182), day of quarter(1-92) and day of half quarter(1-46) columns to my dataframe w.r.t date.

In R we can use 
df$half_year = df$yearday %% 182

Can anyone help me with this?

CodePudding user response:

the pandas.Timestamp has a descriptor called dayofyear which you can call like this: pd.Timestamp.dayofyear

import pandas as pd

# create dates
some_dates = pd.date_range(
    start=pd.to_datetime('07-02-1990', format='%m-%d-%Y'),
    end=pd.to_datetime('07-04-1990', format='%m-%d-%Y'),
)

# store in pandas df
some_df = pd.DataFrame()
some_df['Date'] = some_dates

# get day of years
some_df['day_of_year'] = some_df.Date.dt.dayofyear
some_df['day_of_half_year'] = some_df.Date.dt.dayofyear % 182
print(some_df)

>>> Date                day_of_year  day_of_half_year
0   1990-07-02          183                 1
1   1990-07-03          184                 2
2   1990-07-04          185                 3
  • Related