首页 > 解决方案 > 将索引转换为时间序列索引 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

谢谢,如果有人可以提供帮助,我真的很感激

标签: pythonpandasdataframedatetimegoogle-colaboratory

解决方案


您可以转换indexSeries,移位和比较索引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')

推荐阅读