Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python的日期框中更改从月初到月底的日期_Python_Pandas - Fatal编程技术网

如何在Python的日期框中更改从月初到月底的日期

如何在Python的日期框中更改从月初到月底的日期,python,pandas,Python,Pandas,例如,我有以下数据框: index 0 2000-03-01 4.03333 2000-06-01 3.93333 2000-09-01 4.0 2000-12-01 3.9 2001-03-01 4.23333 2001-06-01 4.4 索引为pandas.tseries.index.DatetimeIndex类型。我想把指数从月初改到月底,比如说,所有指数的2000-03-01改为2000-03-31。我怎样才能做到这一点呢?这里介绍如何将指数移动到每个月底。

例如,我有以下数据框:

index        0
2000-03-01  4.03333
2000-06-01  3.93333
2000-09-01  4.0
2000-12-01  3.9
2001-03-01  4.23333
2001-06-01  4.4

索引为pandas.tseries.index.DatetimeIndex类型。我想把指数从月初改到月底,比如说,所有指数的
2000-03-01
改为
2000-03-31
。我怎样才能做到这一点呢?

这里介绍如何将指数移动到每个月底。您可以通过更改
freq
参数来选择不同的频率(请参阅)


您可以使用
t系列.偏移量
并使用:


我尝试使用datetime.replace()函数替换日期。但不知何故,它不工作。考虑提供最低数量的代码,让其他人检查和排除问题,你有…实际上,我真的很新的Python,我只是不知道如何做到这一点。谢谢这是个问题应该是2000-09-30我已经更新了我的答案。现在使用
M
频率是正确的。
# Sample data
df = pd.DataFrame({'0': [4.0333300000000003,
  3.9333300000000002,
  4.0,
  3.8999999999999999,
  4.2333300000000005,
  4.4000000000000004]},
 index = pd.to_datetime(['2000-03-01',
  '2000-06-01',
  '2000-09-01',
  '2000-12-01',
  '2001-03-01',
  '2001-06-01']))

# Shifting
df.shift(periods=1, freq='M')

                  0
2000-03-31  4.03333
2000-06-30  3.93333
2000-09-30  4.00000
2000-12-31  3.90000
2001-03-31  4.23333
2001-06-30  4.40000
In [143]:
from pandas.tseries.offsets import *
df.index += MonthEnd()
df

Out[143]:
                  0
index              
2000-03-31  4.03333
2000-06-30  3.93333
2000-09-30  4.00000
2000-12-31  3.90000
2001-03-31  4.23333
2001-06-30  4.40000