ton*_*ony 36 datetime python-3.x pandas
我想从pandas数据框中的数据中提取一周数.
日期格式为datetime64 [ns]
我已将日期标准化以从中删除时间
df['Date'] = df['Date'].apply(pd.datetools.normalize_date)
Run Code Online (Sandbox Code Playgroud)
所以日期现在看起来像 - 2015-06-17在数据框列中
现在我想将其转换为周数.
提前致谢
EdC*_*ica 57
只需访问dt周属性:
In [286]:
df['Date'].dt.week
Out[286]:
0 25
dtype: int64
In [287]:
df['Week_Number'] = df['Date'].dt.week
df
Out[287]:
Date Week_Number
0 2015-06-17 25
Run Code Online (Sandbox Code Playgroud)
Axe*_*xel 21
这是使用的另一种可能性strftime.strftime.org是一个很好的资源.
df['Week_Number'] = df['Date'].dt.strftime('%U')
Run Code Online (Sandbox Code Playgroud)
'%U'表示一年的周数(星期日作为一周的第一天)作为零填充十进制数.在第一个星期日之前的新年中的所有日子都被认为是在第0周.
如果您有多年的日期,我建议您创建一个年 - 周组合
df['Year-Week'] = df['Date'].dt.strftime('%Y-%U')
Run Code Online (Sandbox Code Playgroud)
Art*_*sky 13
Pandas has its .dayofyear and .weekofyear functionality, which can be applied straight away to the output of pandas.to_datetime(df['column_name']), giving type "Timestamp" as the output.
import pandas as pd
df['formatted_date'] = pd.to_datetime(df['datetime'])
df['day_of_year'] = df.formatted_date.apply(lambda x: x.dayofyear)
df['week_of_year'] = df.formatted_date.apply(lambda x: x.weekofyear)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48639 次 |
| 最近记录: |