gpt4 book ai didi

python - pandas 获取前一个日期的索引

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:41 25 4
gpt4 key购买 nike

我有带有日期列的 pandas 数据框,我想在数据框中添加带有先前日期索引的新列。如何实现这一目标?示例 df:

index Date
0 2015-10-03
1 2015-11-03
2 2015-11-30
3 2015-11-30
4 2015-12-03

期望的输出:

index Date previous_day
0 2015-10-03 0
1 2015-11-03 0
2 2015-11-30 1
3 2015-11-30 1
4 2015-12-03 3
  1. 由于索引 1 处没有前一天,所以我想要前一天为 1。
  2. 由于索引 2 的日期与索引 3 相同,因此我预计索引 3 的 previous_day 中的日期为 1。

谢谢

最佳答案

我认为您需要将Date列的重复值的index替换为NaN,然后转发填充这些值(value)观。还需要将索引的第一个值重命名为 1 并最后减去 1:

注意:解决方案仅在唯一单调索引 (0,1,2,...) 时有效

#see notice above 
df.reset_index(drop = True, inplace = True)

df['prev'] = df.rename(index={0:1})
.index.to_series()
.where(~df['Date'].duplicated()).ffill()
.astype(int)
.sub(1).values
print (df)
Date prev
index
0 2015-10-03 0
1 2015-11-03 0
2 2015-11-30 1
3 2015-11-30 1
4 2015-12-03 3

关于python - pandas 获取前一个日期的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44430037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com