【问题标题】:finding first and last available days of a month in pandas在熊猫中查找一个月的第一天和最后一天
【发布时间】:2021-07-08 17:12:08
【问题描述】:

我有一个 2007 年到 2017 年的 pandas 数据框。数据是这样的:

date      closing_price
2007-12-03  728.73
2007-12-04  728.83
2007-12-05  728.83
2007-12-07  728.93
2007-12-10  728.22
2007-12-11  728.50
2007-12-12  728.51
2007-12-13  728.65
2007-12-14  728.65
2007-12-17  728.70
2007-12-18  728.73
2007-12-19  728.73
2007-12-20  728.73
2007-12-21  728.52
2007-12-24  728.52
2007-12-26  728.90
2007-12-27  728.90
2007-12-28  728.91
2008-01-05  728.88
2008-01-08  728.86
2008-01-09  728.84
2008-01-10  728.85
2008-01-11  728.85
2008-01-15  728.86
2008-01-16  728.89

如您所见,每个月都会缺少一些日子。我想获取每个月的第一天和最后一个“可用”天,并计算它们的 close_price 的差异,并将结果放入一个新的数据框中。例如第一个月,天数是 2007-12-03 和 2007-12-28,收盘价是 728.73 和 728.91,所以结果是 0.18。我怎样才能做到这一点?

【问题讨论】:

  • 您能分享一下您为实现这一目标所做的工作吗?

标签: python pandas timestamp dayofmonth


【解决方案1】:

您可以按月对 df 进行分组并应用一个函数来执行此操作。请注意to_period,该函数将 DataFrame 从 DatetimeIndex 转换为 PeriodIndex 并以所需的频率。

def calculate(x):
    start_closing_price = x.loc[x.index.min(), "closing_price"]
    end_closing_price = x.loc[x.index.max(), "closing_price"]
    return end_closing_price-start_closing_price

result = df.groupby(df["date"].dt.to_period("M")).apply(calculate)

# result
date
2007-12    0.18
2008-01    0.01
Freq: M, dtype: float64

【讨论】:

    【解决方案2】:

    首先确保它们是datetime 并已排序:

    import pandas as pd
    
    df['date'] = pd.to_datetime(df.date)
    df = df.sort_values('date')
    

    分组方式

    gp = df.groupby([df.date.dt.year.rename('year'), df.date.dt.month.rename('month')])
    gp.closing_price.last() - gp.closing_price.first()
    
    #year  month
    #2007  12       0.18
    #2008  1        0.01
    #Name: closing_price, dtype: float64
    

    gp = df.groupby(pd.Grouper(key='date', freq='1M'))
    gp.last() - gp.first()
    
    #            closing_price
    #date                     
    #2007-12-31           0.18
    #2008-01-31           0.01
    

    重新采样

    gp = df.set_index('date').resample('1M')
    gp.last() - gp.first()
    
    #            closing_price
    #date                     
    #2007-12-31           0.18
    #2008-01-31           0.01
    

    【讨论】:

      【解决方案3】:

      问题:获取索引数据帧的第一个或最后一个日期

      解决方案:重新采样索引,然后提取数据。

      lom    = pd.Series(x.index, index = x.index).resample('m').last()
      xlast  = x[x.index.isin(lom)] # .resample('m').last() to get monthly freq
      
      fom    = pd.Series(x.index, index = x.index).resample('m').first()
      xfirst = x[x.index.isin(fom)]
      

      【讨论】:

      • 取差价,xlast.resamlpe('m').last() - xfirst.resample('m').last() 但您通常希望每月更改:xlast.diff()
      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 2015-02-06
      • 2016-02-09
      • 2015-07-09
      • 2013-07-07
      • 2011-01-04
      相关资源
      最近更新 更多