熊猫:如何创建年周变量?

ℕʘʘ*_*ḆḽḘ 2 python dataframe pandas

我有一个带有日期时间的数据框

dates = pd.date_range('9/25/2010', periods=10, freq='D')

df = pd.DataFrame({'col':dates})
df['col']=pd.to_datetime(df['col'])
df['dow'] = df.col.dt.dayofweek
df['week'] = df.col.dt.to_period('W')
df['week_alt']=df.col.dt.year.astype(str) + '-w' + df.col.dt.week.astype(str)

df
Out[21]: 
         col  dow                  week  week_alt
0 2010-09-25    5 2010-09-20/2010-09-26  2010-w38
1 2010-09-26    6 2010-09-20/2010-09-26  2010-w38
2 2010-09-27    0 2010-09-27/2010-10-03  2010-w39
3 2010-09-28    1 2010-09-27/2010-10-03  2010-w39
4 2010-09-29    2 2010-09-27/2010-10-03  2010-w39
5 2010-09-30    3 2010-09-27/2010-10-03  2010-w39
6 2010-10-01    4 2010-09-27/2010-10-03  2010-w39
7 2010-10-02    5 2010-09-27/2010-10-03  2010-w39
8 2010-10-03    6 2010-09-27/2010-10-03  2010-w39
9 2010-10-04    0 2010-10-04/2010-10-10  2010-w40
Run Code Online (Sandbox Code Playgroud)

在这里,您可以看到一个星期开始于Monday结束Sunday

我想控制一周的开始时间。例如,如果几周现在改为从周日开始, 2010-09-26则将是2010-w392010-10-032010-w40

如何在熊猫中做到这一点?

Max*_*axU 6

UPDATE:你可以这三个UNIX修改器之间进行选择:%U%V%W

%U年中的第 几周,星期天是星期几(00..53)。

%V ISO周编号,星期一为一周的第一天(01..53)。

年的%W 周数,星期一为一周的第一天(00..53)。

In [189]: df.col.dt.strftime('%U-%V-%W')
Out[189]:
0    38-38-38
1    39-38-38
2    39-39-39
3    39-39-39
4    39-39-39
5    39-39-39
6    39-39-39
7    39-39-39
8    40-39-39
9    40-40-40
Name: col, dtype: object
Run Code Online (Sandbox Code Playgroud)

%U 一年中的第几周,星期日是一周的第一天(00..53)。

In [190]: df.col.dt.strftime('%Y-w%U')
Out[190]:
0    2010-w38
1    2010-w39
2    2010-w39
3    2010-w39
4    2010-w39
5    2010-w39
6    2010-w39
7    2010-w39
8    2010-w40
9    2010-w40
Name: col, dtype: object
Run Code Online (Sandbox Code Playgroud)

%V ISO周编号,星期一为一周的第一天(01..53)。

In [191]: df.col.dt.strftime('%Y-w%V')
Out[191]:
0    2010-w38
1    2010-w38
2    2010-w39
3    2010-w39
4    2010-w39
5    2010-w39
6    2010-w39
7    2010-w39
8    2010-w39
9    2010-w40
Name: col, dtype: object
Run Code Online (Sandbox Code Playgroud)

  • 逐年增加一周通常会在一年的第一天返回错误的转换:1/1/2017 返回为 2017-w52,这显然是错误的。 (2认同)