【问题标题】:How do I select data between different weeks and group them to store the sliced DataFrame according week in an array?,如何选择不同周之间的数据并将它们分组以根据周将切片的 DataFrame 存储在数组中?
【发布时间】:2020-08-11 20:43:12
【问题描述】:

我想获得以下数据框的每周高低收盘价 所以我想根据周对DataFrame进行切片并存储在一个数组中

  • 日期开盘高低收盘

  • 01-08-2019 | 97.85 | 98.45 | 96.40 97.25


  • 02-08-2019 | 97.15 | 98.95 | 96.75 98.15

  • 05-08-2019 | 98.30 | 98.70 | 94.30 95.65

  • 06-08-2019 | 95.75 | 97.75 | 95.20 97.05

  • 07-08-2019 | 96.80 | 97.70 | 96.05 96.90

  • 08-08-2019 | 97.40 | 98.90 | 96.55 97.40

  • 09-08-2019 | 97.20 | 98.10 | 96.65 97.30

  • 12-08-2019 | 97.20 | 97.25 | 93.40 93.75

  • 13-08-2019 | 93.70 | 96.60 | 93.15 96.35

  • 14-08-2019 | 95.85 | 96.40 | 94.00 94.45

8 月 01-08-2019 ,02-08-2019 是一周。 八月 05-08-2019, 06-08-2019, 07-08-2019, 08-08-2019, 09-08-2019 是第二周 我希望数据框中的数据应按周分组。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    要更改基于时间的数据帧的频率,您可以使用resample method。以下代码应该可以工作:

    (
        df
        .assign(Date=lambda x: pd.to_datetime(x['Date'], dayfirst=True)
        .set_index('Date')
        .asfreq('D')
        .resample('W')
        .agg({
           'High': 'max',
           'Low': 'min',
           'Open': lambda x: x.dropna().iloc[0],
           'Close': lambda x: x.dropna().iloc[-1]
        })
    )
    

    【讨论】:

    • 我现在在您的数据中看到的是日期不是正确的日期,而是DD-MM-YYYY 格式的字符串。请在将日期列用作索引之前将其转换为df['Date']=dp.to_datetime(df['Date'], dayfirst=True)。我将编辑我的答案以涵盖这一点。您也可以忽略 ilocs 上的缺失值。
    • 是的,数据是字符串格式。我改变了,谢谢它的帮助
    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多