我有以下数据框df
:
date USDBRL
0 1994-01-31 458.6600
1 1994-02-28 637.4500
2 1994-03-30 913.3450
3 1994-04-29 1302.2800
4 1994-05-31 1875.2700
.. ... ...
317 2020-06-30 5.4760
318 2020-07-31 5.2033
319 2020-08-31 5.4713
320 2020-09-30 5.6407
321 2020-10-09 5.5393
我想将所有日期
值更改为该月的第一天。
我尝试过这个:
df['date'] = datetime(df['date'].dt.year, df['date'].dt.month, 1)
但我遇到语法错误:
TypeError: cannot convert the series to <class 'int'>
最佳答案
- 使用
pandas.offsets.MonthBegin
将日期设置为月初。 - 还有Pandas: convert date in month to the 1st day of next month
- pandas User Guide: Time series / date functionality
- pandas: Date offsets
方法 1
将日期设置为月初,但如果该日期已经是第一天,则将日期设置为上个月的第一天。方法 2
首先将日期设置为月底,然后设置为月初。
import pandas as pd
# sample data
df = pd.DataFrame({'date': [pd.Timestamp('1994-01-31 00:00:00'), pd.Timestamp('1994-02-28 00:00:00'), pd.Timestamp('1994-03-30 00:00:00'), pd.Timestamp('1994-04-29 00:00:00'), pd.Timestamp('1994-05-31 00:00:00'), pd.Timestamp('2010-01-01 00:00:00'), pd.Timestamp('2010-01-31 00:00:00'), pd.Timestamp('2010-03-02 00:00:00'), pd.Timestamp('2010-04-01 00:00:00'), pd.Timestamp('2010-05-01 00:00:00'), pd.Timestamp('2010-05-31 00:00:00'), pd.Timestamp('2020-06-30 00:00:00'), pd.Timestamp('2020-07-31 00:00:00'), pd.Timestamp('2020-08-31 00:00:00'), pd.Timestamp('2020-09-30 00:00:00'), pd.Timestamp('2020-10-09 00:00:00')]})
# method 1
df['m1'] = df.date - pd.offsets.MonthBegin(1)
# method 2
df['m2'] = df.date - pd.offsets.MonthEnd(0) - pd.offsets.MonthBegin(1)
- 如ALollz所述在评论中,如果该月的某一天已经是第一天,则
方法 1
可能会出现问题。- 根据他的建议,有一个更强大的解决方案,
方法 2
,该解决方案占了 1 日的天数。
- 根据他的建议,有一个更强大的解决方案,
关于python - 如何将日期时间中的日期更改为当月的第一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64285941/