Luc*_*esl 0 python datetime week-number pandas
我正在尝试转换以下数据框
id year week
1 2018 43
1 2019 1
2 2019 4
3 2018 51
Run Code Online (Sandbox Code Playgroud)
到包含以下列的数据框中
id year week year_week
1 2018 43 2018-43
1 2019 1 2019-1
2 2019 4 2019-4
3 2018 51 2018-51
Run Code Online (Sandbox Code Playgroud)
其中“year_week”是日期时间类型
您需要选择一周中的某一天,以便根据该数据创建时间戳。假设这些是ISO 周,我选择“1”作为 ISO 周开始的星期一(还添加了一列以转换为问题中显示的字符串格式)。
如果您确实希望列数据是datetime 对象而不是pandas.Timestamp,请参阅在 datetime 和 Timestamp 对象之间转换,了解您需要包含的另一个步骤。
from datetime import datetime
import pandas as pd
def year_week(y, w):
return datetime.strptime(f'{y} {w} 1', '%G %V %u')
df = pd.DataFrame([(2018, 43), (2019, 1), (2019, 4), (2018, 51)], columns=['year', 'week'])
df['year_week_ts'] = df.apply(lambda row: year_week(row.year, row.week), axis=1)
df['year_week_str'] = df.apply(lambda row: row.year_week_ts.strftime('%G-%V'), axis=1)
print(df)
# year week year_week_ts year_week_str
# 0 2018 43 2018-10-22 2018-43
# 1 2019 1 2018-12-31 2019-01
# 2 2019 4 2019-01-21 2019-04
# 3 2018 51 2018-12-17 2018-51
# for python 3 versions pre-3.6 use '{} {} 1'.format(y, w) instead of the f string above
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2986 次 |
| 最近记录: |