【问题标题】:Find a one year date from now in Python/Pandas with approximations在 Python/Pandas 中使用近似值查找一年后的日期
【发布时间】:2017-08-31 21:02:42
【问题描述】:

我有一个 df pandas,列中只有一个“价格”和索引日期。我想在里面找到一个名为“Aprox”的新列

 aprox. = price of today - price of one year ago (or closest date from a year ago) - 
price in one year (again take aprox if exact one year price don't exist)
 for example   
 aprox. 2019-04-30 = 8 -4 -10 = -6 = aprox. 2019-04-30
                                            - aprox. 2018-01-31 - aprox.2020-07-30  

说实话,我有点挣扎......

ex. [in]:      Price
2018-01-31       4  
2019-04-30       8 
2020-07-30       10   
2020-10-31       9  
2021-01-31       14   
2021-04-30       150
2021-07-30       20
2022-10-31       14

   [out]:      Price    aprox.
2018-01-31       4  
2019-04-30       8       -6  ((8-4-10) = -6) since there is no 2018-04-30 
2020-07-30       10      -12 (10-14-8)
2020-10-31       9       ...
2021-01-31       14      ...
2021-04-30       150
2021-07-30       20
2022-10-31       14

我对此非常苦恼......甚至更多的是大约。

非常感谢!!

【问题讨论】:

    标签: python python-2.7 date pandas dataframe


    【解决方案1】:

    我不太清楚你想要做什么,但也许这就是你想要的:

    import pandas
    
    def last_year(x):
        """
        Return date from a year ago.
        """
        return x - pandas.DateOffset(years=1)
    
    # Simulate the data you provided in example
    dt_str = ['2018-01-31', '2019-04-30', '2020-07-30', '2020-10-31',
              '2021-01-31', '2021-04-30', '2021-07-30', '2022-10-31']
    dates = [pandas.Timestamp(x) for x in dt_str]
    df = pandas.DataFrame([4, 8, 10, 9, 14, 150, 20, 14], columns=['Price'], index=dates)
    
    # This is the code that does the work
    for dt, value in df['Price'].iteritems():
        df.loc[dt, 'approx'] = value - df['Price'].asof(last_year(dt))
    

    这给了我以下结果:

    In [147]: df
    Out[147]:
                  Price  approx
    2018-01-31      4     NaN
    2019-04-30      8     4.0
    2020-07-30     10     2.0
    2020-10-31      9     1.0
    2021-01-31     14     6.0
    2021-04-30    150   142.0
    2021-07-30     20    10.0
    2022-10-31     14    -6.0
    

    底线是,对于这种类型的操作,您不能只使用apply 操作,因为您需要索引和值。

    【讨论】:

    • 您好,感谢您的回复@aquil.abdullah!这不正是我要找的。例如,对于 2019 年 4 月 30 日,“大约”列应返回 2019 年 4 月 30 日的价格(此处为 8)减去一年前的价格减去一年后的价格。如果在我的数据集中没有确切年份之前或之后的价格,我只想取这一年最接近的价格/日期,所以这里是 2020-07-30 和 2018-01-31 的价格。微积分应该是 8 - 4 - 10 = - 6
    猜你喜欢
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多