python - 将索引转换为时间序列索引 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')
推荐阅读
- reactjs - 下拉 onchange 不起作用:React+ Typescript+ semantic-ui-react
- db2 - 删除语句需要很长时间
- javascript - 只需要片段时在jQuery中拉页面
- javascript - 无法获取 JSON 数组名称包含连字符(“-”(例如:item.media-metadata[0].url)
- python - StanfordCoreNLP 英文 upos 注释
- excel - Microsoft Navision PMT 公式
- css - 无法让 CSS 格式和脚本在 HTA 中协同工作
- java - 从 Java(和 Kotlin)隐藏 Kotlin 对象的实例字段
- tableau-api - 无法从 tableau 服务器获取令牌
- java - 如何在 Spring Boot 中跟踪/监视套接字连接?