python - 将数据帧年份和月份合并到新对象Python中

标签 python python-3.x pandas date dataframe

我有一个数据框,其中只有年份和月份的分隔列,例如:

Year        Month
2001        1
2001        2
2001        3
.
.
2010        1
2010        2
.

使用 pd.to_datetime(df[['year', 'month']]) 转换为 pd.datetime 需要几天来匹配格式,所以我得到错误:

ValueError:组装映射至少需要指定[年、月、日]:缺少[日]

我觉得我可以重复填写一个新列,其中 Day = 1 重复,但我想避免这种情况,因为我只想按年-月创建一个时间序列。

有没有办法将年月映射到日期以正确绘制图表?

最佳答案

不存在只有一个月的日期时间之类的事情。

pd.to_datetime

assign 使用参数中指定的列创建 df 的副本。

@timgeb声明:

Explanation: df.assign(day=1) is a quick way to create a temporary dataframe with a 'day' column without having to modify your original dataframe.

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

关于python - 将数据帧年份和月份合并到新对象Python中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53271332/

相关文章:

python pandas : How to simplify the result of groupby ('column_name' ). count()

python - Pandas - 根据其他列中的值将数据添加到列

python - "not in"身份运算符在检查某些字符的空字符串时不起作用

python - Google Stackdriver 使用 Redis 队列登录 App Engine (Python)

python-3.x - selenium.common.exceptions.WebDriverException : Message: unknown error: unable to discover open pages using ChromeDriver through Selenium

python - 如何将 unicode 转换为 unicode 转义文本

python - 如何在sqlite3中同时搜索多个表?

python - Biopython 全局对齐 : Out of Memory

python-3.x - 谷歌云功能错误与轮子和pywin32

Python Matplotlib : Splitting one Large Graph into several Sub-Graphs (Subplot)