python - 将数据框年份和月份组合到新对象Python中
问题描述
我有一个数据框,其中只有年和月的单独列,例如:
Year Month
2001 1
2001 2
2001 3
.
.
2010 1
2010 2
.
转换为pd.datetime
usingpd.to_datetime(df[['year', 'month']])
需要几天才能匹配格式,所以我收到错误:
ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day] is missing
我觉得我可以用 Day = 1 重复填充一个新列,但我想避免这种情况,因为我只想按年创建一个时间序列。
有没有办法将年月映射到日期以正确绘制图表?
解决方案
没有只有一个月的事情datetime
。
pd.to_datetime
assign
df
使用 arguments` 中指定的列创建副本。
正如@timgeb所说:
说明:是一种无需修改原始数据框
df.assign(day=1)
即可创建带有列的临时数据框的快速方法。'day'
pd.to_datetime(df.assign(day=1))
0 2001-01-01
1 2001-02-01
2 2001-03-01
3 2010-01-01
4 2010-02-01
dtype: datetime64[ns]
to_period
您可能想要使用to_period
.
pd.to_datetime(df.assign(day=1)).dt.to_period('M')
0 2001-01
1 2001-02
2 2001-03
3 2010-01
4 2010-02
dtype: object
推荐阅读
- .net - 当 ServiceCertificate.Authentication.CertificateValidationMode 设置为 none 时会出现什么样的特定风险
- php - Laravel:目标在构建时不可实例化
- android - Proguard:如何保持内部@interfaces?
- c++ - 使用全局 IP 地址时,C++ winsock 2 应用程序中的代码是否必须更改?
- docker - 使用 Neo4j 和 docker-compose 配置环境变量
- wordpress - 标题分隔符问题 wordpress
- mysql - 由于二级子查询嵌套导致的未知列
- r - R-markdown self_contained
- javascript - OpenTok JS websocket连接超时问题
- java - 如何将相机拍摄的图像以实际尺寸发送到服务器?