首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用近似值在Python/Pandas中查找一年后的日期

使用近似值在Python/Pandas中查找一年后的日期
EN

Stack Overflow用户
提问于 2017-04-06 10:57:39
回答 1查看 791关注 0票数 0

我有一个df熊猫,在列中只有一个‘价格’和索引日期。我想找一个名为'Aprox‘的新栏目,里面有

代码语言:javascript
复制
 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  

老实说,我对此有点纠结……

代码语言:javascript
复制
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

我很纠结于这一点...更多的是与约。

非常感谢!

EN

回答 1

Stack Overflow用户

发布于 2017-04-06 12:24:04

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

代码语言:javascript
复制
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))

这给了我以下结果:

代码语言:javascript
复制
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操作,因为您同时需要索引和值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43244893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档