How can I make a new Column “Week” into a dataframe in pandas?

Tags: , ,



My code is as follows:

my_dict = {
    "Date": pd.date_range('2020', freq='D', periods=100),
    "Open": np.random.randn(100),
    "High": np.random.randn(100),
    "Low": np.random.randn(100),
    "Close": np.random.randn(100),
    "Volume": np.random.randn(100),
}

df = pd.DataFrame(my_dict)
display(df)

How can I add “Week” column and values like “2020-01”, “2020-02”?

“2020-01” means the first week of 2020.

Answer

Get the year using dt year attribute and concatenate with week attribute. zfill is to fill leading zeros.

(df['Date'].dt.year.astype(str)
     .str.cat(df['Date'].dt.week.astype(str).str.zfill(2),
              sep='-'))

    0     2020-01
    1     2020-01
    2     2020-01
    3     2020-01
    4     2020-01
           ...   
    95    2020-14
    96    2020-15
    97    2020-15
    98    2020-15
    99    2020-15


Source: stackoverflow