为了账号安全,请及时绑定邮箱和手机立即绑定

在索引中插入缺失的季度收益日期

在索引中插入缺失的季度收益日期

PHP
慕哥9229398 2023-11-09 21:20:28
我有这个 df:            revenue   pct_yoy   pct_qoq2020-06-30   99.721  0.479013  0.0928332020-03-31   91.250  0.478283  0.0872162019-12-31   83.930  0.676253  0.1350942019-09-30   73.941       NaN  0.0966572019-06-30   67.424       NaN  0.0922932019-03-31   61.727       NaN  0.2328142018-09-30   50.070       NaN       NaN但是,如果您使用 来查看最后一个索引值,则在将索引视为连续的季度时间序列时,2018我似乎会丢失。2018-12-31该指数直接跳至2018-9-30。如何确保插入任何缺失的季度日期及其nan各自列的值?我不太确定如何解决这个问题。
查看完整描述

2 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

您需要生成自己的季度日期列表,其中包括缺失的日期。然后您可以使用.reindex将数据框重新对齐到这个新的日期列表。


# Get the oldest and newest dates which will be the bounds

#  for our new Index

first_date = df.index.min()

last_date = df.index.max()


# Generate dates for every 3 months (3M) from first_date up to last_date

quarterly = pd.date_range(first_date, last_date, freq="3M")


# realign our dataframe using our new quarterly date index

#  this will fill NaN for dates that did not exist in the

#  original index

out = df.reindex(quarterly)


# if you want to order this from most recent date to least recent date 

#  do: out.sort_index(ascending=False)

print(out)

            revenue   pct_yoy   pct_qoq

2018-09-30   50.070       NaN       NaN

2018-12-31      NaN       NaN       NaN

2019-03-31   61.727       NaN  0.232814

2019-06-30   67.424       NaN  0.092293

2019-09-30   73.941       NaN  0.096657

2019-12-31   83.930  0.676253  0.135094

2020-03-31   91.250  0.478283  0.087216

2020-06-30   99.721  0.479013  0.092833


查看完整回答
反对 回复 2023-11-09
?
守着一只汪

TA贡献1872条经验 获得超3个赞

如果您的数据仅包含示例中的季度末日期,您可以使用resample和asfreq来填充缺失的quarter-ends


df_final = df.resample('Q').asfreq()[::-1]


Out[122]:

            revenue   pct_yoy   pct_qoq

2020-06-30   99.721  0.479013  0.092833

2020-03-31   91.250  0.478283  0.087216

2019-12-31   83.930  0.676253  0.135094

2019-09-30   73.941       NaN  0.096657

2019-06-30   67.424       NaN  0.092293

2019-03-31   61.727       NaN  0.232814

2018-12-31      NaN       NaN       NaN

2018-09-30   50.070       NaN       NaN


查看完整回答
反对 回复 2023-11-09
  • 2 回答
  • 0 关注
  • 72 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信