【问题标题】:Performing pct_change() that only considers the prior year in a time-series dataframe?执行 pct_change() 只考虑时间序列数据帧中的前一年?
【发布时间】:2017-12-24 08:06:36
【问题描述】:

我有一个示例数据框“df”:

df = pd.DataFrame({'Year': [2000, 2002, 2003, 2004], 
                   'Name': ['A'] * 4, 
                   'Value': [4, 1, 1, 3]})

当我执行 pct_change() 即

df['change'] = df['Value'].pct_change()

Year = 2002 行的计算“变化”值为 -0.75。由于缺少 2001 年的数据,我如何让 Pandas 返回 2002 年的 N/A,因为我只想考虑时间序列中的前一年?

干杯。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用set_index + reindex + pct_changefill_method=None -

    1. 首先,设置Year为索引
    2. 获取从最小值到最大值的年份范围,并使用此范围重新索引数据框。缺少的年份现在添加为NaNs
    3. Value 上调用pct_change,无需填充NaNs。
    r = np.arange(df.Year.min(), df.Year.max() + 1)
    df = df.set_index('Year').reindex(r)
    
    v = df['Value'].pct_change(fill_method=None)
    df = df.assign(Change=v).dropna(how='all').reset_index()
    
    df
    
       Year Name  Value  Change
    0  2000    A    4.0     NaN
    1  2002    A    1.0     NaN
    2  2003    A    1.0     0.0
    3  2004    A    3.0     2.0
    

    【讨论】:

    • 谢谢。如何将此解决方案扩展到具有不同年份值范围的多个“名称”ID(例如“B”、“C”等)?
    • @user2530766 你可以groupbyName。代码需要稍作改动。你能用适当的数据样本打开一个新问题吗?
    • 多个ID的后续问题:stackoverflow.com/questions/47960566/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多