Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

python - Problem Converting Index To TimeSeries Index Pandas

I have a problem converting index to time series index pandas i have dataframe:

df['Book Value Per Share *xa0IDR']

Output :

    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

I want to convert TTM to data that corresponds to add to the index behind it by 1 year forward example :

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

Becomes :

 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

thank you I really appreciate it if anyone can help

question from:https://stackoverflow.com/questions/65950687/problem-converting-index-to-timeseries-index-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can convert index to Series, shifting and compare index by TTM, filter and add one year, last convert back to YYYY-MM string and pass to 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

Last if need DatetimeIndex:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...