python-3.8 - Pandas 1.0 从年份和日期创建月份列
问题描述
我有一个数据框df
,其值为:
df.iloc[1:4, 7:9]
Year Month
38 2020 4
65 2021 4
92 2022 4
我正在尝试创建一个新MonthIdx
列:
df['MonthIdx'] = pd.to_timedelta(df['Year'], unit='Y') + pd.to_timedelta(df['Month'], unit='M') + pd.to_timedelta(1, unit='D')
但我得到了错误:
ValueError: Units 'M' and 'Y' are no longer supported, as they do not represent unambiguous timedelta values durations.
以下是所需的输出:
df['MonthIdx']
MonthIdx
38 2020/04/01
65 2021/04/01
92 2022/04/01
解决方案
因此,您可以在系列中填充月份值,然后重新格式化以获得所有值的日期时间:
month = df.Month.astype(str).str.pad(width=2, side='left', fillchar='0')
df['MonthIdx'] = pd.to_datetime(pd.Series([int('%d%s' % (x,y)) for x,y in zip(df['Year'],month)]),format='%Y%m')
这会给你:
Year Month MonthIdx
0 2020 4 2020-04-01
1 2021 4 2021-04-01
2 2022 4 2022-04-01
您可以将日期重新格式化为字符串以完全匹配您的格式:
df['MonthIdx'] = df['MonthIdx'].apply(lambda x: x.strftime('%Y/%m/%d'))
给你:
Year Month MonthIdx
0 2020 4 2020/04/01
1 2021 4 2021/04/01
2 2022 4 2022/04/01
推荐阅读
- algorithm - log(nf(n)) 是 log(n) 的大 theta
- typescript - 在 VS Code 中折叠 tsx 文件中的类型定义
- spring - 如何测试具有假装客户端的休息控制器?
- java - Android - 带有监听器的 Firestore 无限分页
- python - 自定义 Django 管理站点
- office365 - PowerApps - 无法将 SharePoint 人员/人员字段设置为当前用户
- amazon-web-services - 如何使用 Node.js 向 Lambda-AWS 写入和读取文件
- git - 为什么 git 看到我的提交但没有将更改应用到代码库?
- javascript - 如何读取javascript枚举值
- node.js - 我可以在 mongodb 的一个对象中添加所有用户数据吗?