• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python Pandas:每月或每周拆分 TimeSerie

用户头像
it1352
帮助1

问题说明

我有一个跨越几年的 Timeserie,格式如下:

I have a Timeserie that spans few year, in the following format:

              timestamp open    high    low    close    volume
0   2009-01-02 05:00:00 900.00  906.75  898.00  904.75  15673.0
1   2009-01-02 05:30:00 904.75  907.75  903.75  905.50  4600.0
2   2009-01-02 06:00:00 905.50  907.25  904.50  904.50  3472.0
3   2009-01-02 06:30:00 904.50  905.00  903.25  904.75  6074.0
4   2009-01-02 07:00:00 904.75  905.50  897.00  898.25  12538.0

将该数据帧拆分为多个数据帧(包含 1 周或 1 个月的数据)的最简单方法是什么?77

What would be the simplest way to split that dataframe into multiple dataframes of 1 week or 1 month worth of data?77

例如,包含 1 年数据的数据帧将被拆分为 52 个包含一周数据的数据帧,并作为 52 个数据帧的列表返回

as an example a dataframe containing 1 year of data would be split in 52 dataframes containing a week of data and returned as a list of 52 dataframes

(数据可以用下面的公式重构)

(the data can be reconstructed with the formula below)

import pandas as pd
from pandas import Timestamp
dikt={'close': {0: 904.75, 1: 905.5, 2: 904.5, 3: 904.75, 4: 898.25}, 'low': {0: 898.0, 1: 903.75, 2: 904.5, 3: 903.25, 4: 897.0}, 'open': {0: 900.0, 1: 904.75, 2: 905.5, 3: 904.5, 4: 904.75}, 'high': {0: 906.75, 1: 907.75, 2: 907.25, 3: 905.0, 4: 905.5}, 'volume': {0: 15673.0, 1: 4600.0, 2: 3472.0, 3: 6074.0, 4: 12538.0}, 'timestamp': {0: Timestamp('2009-01-02 05:00:00'), 1: Timestamp('2009-01-02 05:30:00'), 2: Timestamp('2009-01-02 06:00:00'), 3: Timestamp('2009-01-02 06:30:00'), 4: Timestamp('2009-01-02 07:00:00')}}
pd.DataFrame(dikt, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])

正确答案

#1

groupbypd.TimeGrouper 和列表推导一起使用

use groupby with pd.TimeGrouper and list comprehensions

weeks = [g for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('W'))]
months = [g for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('M'))]

<小时>

如果需要,您可以重置索引


You can reset the index if you need

weeks = [g.reset_index()
         for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('W'))]
months = [g.reset_index()
          for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('M'))]

<小时>

dict

weeks = {n: g.reset_index()
         for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('W'))}
months = {n: g.reset_index()
          for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('M'))}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanghfjai
系列文章
更多 icon
同类精品
更多 icon
继续加载