【问题标题】:Shifting Time Periods and Calculating Delta using Python使用 Python 转换时间段并计算 Delta
【发布时间】:2021-02-04 01:48:54
【问题描述】:

我有一个文件 df,我希望获取每 7 天的增量

df:

Date          Value
10/15/2020    75
10/14/2020    70
10/13/2020    65
10/12/2020    60
10/11/2020    55
10/10/2020    50
10/9/2020     45
10/8/2020     40
10/7/2020     35
10/6/2020     30
10/5/2020     25
10/4/2020     20
10/3/2020     15
10/2/2020     10
10/1/2020     5

所需的输出:

Date          Value

10/9/2020     30
10/2/2020     30

这就是我正在做的事情,感谢这个平台上某人的帮助:

df.Date = pd.to_datetime(df.Date)   

s = df.set_index('Date')['Value']
df['New'] = s.shift(freq = '-6 D').reindex(s.index).values  
df['Delta'] = df['New'] - df['Value'] 

df[['Date','Delta']].dropna()  

但是,这给了我一个正在运行的增量,我希望每 7 天显示一次增量,如所需输出中所示。 任何建议表示赞赏

【问题讨论】:

    标签: python pandas numpy time-series


    【解决方案1】:

    我认为你所做的方式是完美的方式。我认为稍微修改一下会给你想要的结果。试试这个:

     df.Date = pd.to_datetime(df.Date)
     s = df.set_index('Date')['Value']
     df['New'] = s.shift(freq = '-6 D').reindex(s.index).values
     df['Delta'] = df['New'] - df['Value'] 
     df_new=df[['Date','Delta']].dropna()
     df_new.iloc[::7, :]
    

    【讨论】:

    • 嗨@sahil,你能解释一下这是做什么的吗? [::7, :] ?它是否仅提供 Date 和 Value 列的所需输出?谢谢 - 我已经尝试过了,但与原来的不受欢迎的输出相比似乎没有任何改变
    • 它是python中的扩展切片选项,甚至可以检查回文字符串。在这里阅读这篇文章stackoverflow.com/questions/3453085/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多