python - 如何将月份和年份放在 Python Pandas 的同一列中

标签 python pandas datetime

Column1   Month    Quantity Year
48         4         12.00  2006
49         5         13.00  2006
50         6         46.00  2006
51         7         11.00  2006
52         8         18.00  2006
53         9         16.00  2006
54        10         28.00  2006
83         1          6.00  2006

如何将月份列与年份列合并,并获得有意义的时间数据?

最佳答案

In [42]: df['Date'] = pd.to_datetime(df.assign(Day=1).loc[:, ['Year','Month','Day']])

In [43]: df
Out[43]:
   Column1  Month  Quantity  Year       Date
0       48      4      12.0  2006 2006-04-01
1       49      5      13.0  2006 2006-05-01
2       50      6      46.0  2006 2006-06-01
3       51      7      11.0  2006 2006-07-01
4       52      8      18.0  2006 2006-08-01
5       53      9      16.0  2006 2006-09-01
6       54     10      28.0  2006 2006-10-01
7       83      1       6.0  2006 2006-01-01

much nicer solution from @piRSquared :

In [55]: df['Date'] = pd.to_datetime(df[['Year', 'Month']].assign(Day=1))

In [56]: df
Out[56]:
   Column1  Month  Quantity  Year       Date
0       48      4      12.0  2006 2006-04-01
1       49      5      13.0  2006 2006-05-01
2       50      6      46.0  2006 2006-06-01
3       51      7      11.0  2006 2006-07-01
4       52      8      18.0  2006 2006-08-01
5       53      9      16.0  2006 2006-09-01
6       54     10      28.0  2006 2006-10-01
7       83      1       6.0  2006 2006-01-01

关于python - 如何将月份和年份放在 Python Pandas 的同一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214827/

相关文章:

python - 上下文管理器处理路径的类型提示

pandas - 来自 2 个数据框的日期相关计算 - 平均 6 个月的返回

java - 在 Spring 根据请求设置时区

Python docx 属性错误 : 'WindowsPath' object has no attribute 'seek'

python - 在 python 中 reshape 数组乘法/除法

python - 从 Seaborn 调色板中提取 RGB 或 6 位代码

python - 合并3个同名数据库,并在python中重命名它们

python - Pandas :水平扩展/分解数据框

javascript - 如何更改具有不同时区的javascript中的日期

spring - 将 Spring MVC 中的默认/全局日期格式设置为 ISO 8601