My code is as follows:
JavaScript
x
12
12
1
my_dict = {
2
"Date": pd.date_range('2020', freq='D', periods=100),
3
"Open": np.random.randn(100),
4
"High": np.random.randn(100),
5
"Low": np.random.randn(100),
6
"Close": np.random.randn(100),
7
"Volume": np.random.randn(100),
8
}
9
10
df = pd.DataFrame(my_dict)
11
display(df)
12
How can I add “Week” column and values like “2020-01”, “2020-02”?
“2020-01” means the first week of 2020.
Advertisement
Answer
Get the year using dt year attribute and concatenate with week attribute. zfill is to fill leading zeros.
JavaScript
1
16
16
1
(df['Date'].dt.year.astype(str)
2
.str.cat(df['Date'].dt.week.astype(str).str.zfill(2),
3
sep='-'))
4
5
0 2020-01
6
1 2020-01
7
2 2020-01
8
3 2020-01
9
4 2020-01
10
11
95 2020-14
12
96 2020-15
13
97 2020-15
14
98 2020-15
15
99 2020-15
16