gpt4 book ai didi

python - 将 Pandas 数据框中一列的值向前移动一个月

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

有没有办法将 pandas dataframe 中一列的值向前移动一个月? (请注意,我想窃取列值而不是日期值)。例如,如果我有:

           ColumnA   ColumnB
2016-10-01 1 0
2016-09-30 2 1
2016-09-29 5 1
2016-09-28 7 1
.
.
2016-09-01 3 1
2016-08-31 4 7
2016-08-30 4 7
2016-08-29 9 7
2016-08-28 10 7

然后我希望能够移动 ColumnB 中的值 向前一个月,以获得所需的输出:

           ColumnA   ColumnB
2016-10-01 1 1
2016-09-30 2 7
2016-09-29 5 7
2016-09-28 7 7
.
.
2016-09-01 3 7
2016-08-31 3 X
2016-08-30 4 X
2016-08-29 9 x
2016-08-28 10 x

在我的数据中,每个月的值都是固定的(例如,ColumnB 中的值在 9 月为 1),因此每个月的天数略有不同应该不是问题。

这似乎是相关的Python/Pandas - DataFrame Index - Move one month forward ,但在链接的问题中,OP 想要移动整个框架,而我只想移动选定的列。

最佳答案

它不是太优雅,但你可以这样做:

df=df.reset_index()
df['index']=pd.to_datetime(df['index'],infer_datetime_format=True)
df['offset']=df['index']-pd.DateOffset(months=1)
res=df.merge(df,right_on='index',left_on='offset',how='left')

然后从 res 中取出你想要的列

关于python - 将 Pandas 数据框中一列的值向前移动一个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803726/

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