【问题标题】:Time Series using numpy or pandas使用 numpy 或 pandas 的时间序列
【发布时间】:2013-09-18 06:38:13
【问题描述】:

我是 Python 相关环境的初学者,在使用时间序列数据时遇到问题。

以下是我的 OHLC 1 分钟数据。

2011-11-01,9:00:00,248.50,248.95,248.20,248.70
2011-11-01,9:01:00,248.70,249.00,248.65,248.85
2011-11-01,9:02:00,248.90,249.25,248.70,249.15
...
2011-11-01,15:03:00,250.25,250.30,250.05,250.15
2011-11-01,15:04:00,250.15,250.60,250.10,250.60
2011-11-01,15:15:00,250.55,250.55,250.55,250.55
2011-11-02,9:00:00,245.55,246.25,245.40,245.80
2011-11-02,9:01:00,245.85,246.40,245.75,246.35
2011-11-02,9:02:00,246.30,246.45,245.75,245.80
2011-11-02,9:03:00,245.75,245.85,245.30,245.35
...
  1. 我想提取每行最后一个“CLOSE”数据并转换如下数据格式:

    2011-11-01, 248.70, 248.85, 249.15, ... 250.15, 250.60, 250.55
    2011-11-02, 245.80, 246.35, 245.80, ...
    ...
    
  2. 我想计算最高收盘价,它是每天的时间(分钟),如下所示:

    2011-11-01, 10:23:03, 250.55
    2011-11-02, 11:02:36, 251.00
    ....
    

任何帮助将不胜感激。

提前谢谢你,

【问题讨论】:

  • 此数据是否在文件中?你以前用过数据框吗?

标签: python numpy pandas time-series


【解决方案1】:

您可以使用 pandas 库。对于您的数据,您可以获得最大值:

import pandas as pd
# Read in the data and parse the first two columns as a
# date-time and set it as index
df = pd.read_csv('your_file', parse_dates=[[0,1]], index_col=0, header=None)
# get only the fifth column (close)
df = df[[5]]
# Resample to date frequency and get the max value for each day.
df.resample('D', how='max')

如果您还想显示时间,请将它们作为一列保存在 DataFrame 中,并传递一个函数来确定最大关闭值并返回该行:

>>> df = pd.read_csv('your_file', parse_dates=[[0,1]], index_col=0, header=None,
                     usecols=[0, 1, 5], names=['d', 't', 'close'])
>>> df['time'] = df.index
>>> df.resample('D', how=lambda group: group.iloc[group['close'].argmax()])
             close                time
d_t                             
2011-11-01  250.60 2011-11-01 15:04:00
2011-11-02  246.35 2011-11-02 09:01:00

如果您不想列出每天的价格,那么只需每天执行一次 groupby,然后使用分组对象上的 apply 返回每​​个组的所有价格列表:

>>> df.groupby(lambda dt: dt.date()).apply(lambda group: list(group['close']))
2011-11-01    [248.7, 248.85, 249.15, 250.15, 250.6, 250.55]
2011-11-02                    [245.8, 246.35, 245.8, 245.35]

有关更多信息,请查看文档:Time Series

具体数据集的更新:

你的数据集的问题是你有几天没有任何数据,所以作为重采样器传入的函数应该处理这些情况:

def func(group):
    if len(group) == 0:
        return None
    return group.iloc[group['close'].argmax()]
df.resample('D', how=func).dropna()

【讨论】:

  • 谢谢你,维克多。我还有两个问题。 1. 当日高收盘显示时,我如何获得时间? 2.如何获得每一天的接近值并将其列为每天的行? (就像我的问题 1)
  • @user1913171 更新了答案。
  • 非常感谢维克托!你很擅长使用p​​ython向量操作逻辑!
  • @ViktorKerkez 当我运行命令'df.resample('D', how=lambda group: group.iloc[group['close'].argmax()])'时,Python 显示如下错误“IndexError:索引超出范围”。但是,当我将 group['close'].argmax() 更改为 group['close'].max() 时,它会起作用。我该如何解决这个问题?
  • @user1913171 max 正在做完全不同的事情——它返回最大值。您需要argmax,它返回索引中最大值的位置。你用的是什么版本的熊猫?也可以试试ix 而不是iloc
猜你喜欢
  • 2013-09-19
  • 2015-11-21
  • 2015-11-26
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 2016-07-03
  • 2016-04-28
  • 2020-10-10
相关资源
最近更新 更多