将索引转换为时间序列索引时出现问题 Pandas

Problem Converting Index To TimeSeries Index Pandas

我在将索引转换为时间序列索引时遇到问题pandas 我有数据框:

df['Book Value Per Share *\xa0IDR']

输出:

    2010-12        NaN
    2011-12     326.22
    2012-12     484.66
    2013-12     596.52
    2014-12     740.09
    2015-12     878.66
    2016-12    1139.92
    2017-12    1292.85
    2018-12    1417.75
    2019-12    1612.50
    TTM        1567.89
    Name: Book Value Per Share * IDR, dtype: float64

我想将 TTM 转换为对应于在其后面的索引中添加 1 年的数据 示例:

2019-12 + (1 year) = 2020-12 

变成:

 2010-12        NaN
        2011-12     326.22
        2012-12     484.66
        2013-12     596.52
        2014-12     740.09
        2015-12     878.66
        2016-12    1139.92
        2017-12    1292.85
        2018-12    1417.75
        2019-12    1612.50
        2020-12    1567.89
        Name: Book Value Per Share * IDR, dtype: float64

谢谢,如果有人能提供帮助,我将不胜感激

您可以将 index 转换为 Series,按 TTM 移动和比较索引,过滤并添加一年,最后转换回 YYYY-MM 字符串并传递给rename:

s = df.index.to_series().shift()

s1 = pd.to_datetime(s[s.index == 'TTM'], format='%Y-%m') + pd.DateOffset(years=1)
print (s1)
TTM   2020-12-01
dtype: datetime64[ns]

df = df.rename(index=s1.dt.strftime('%Y-%m'))
print (df)
         Book Value Per Share * IDR
2010-12                         NaN
2011-12                      326.22
2012-12                      484.66
2013-12                      596.52
2014-12                      740.09
2015-12                      878.66
2016-12                     1139.92
2017-12                     1292.85
2018-12                     1417.75
2019-12                     1612.50
2020-12                     1567.89

最后如果需要 DatetimeIndex:

df.index = pd.to_datetime(df.index, format='%Y-%m')