【发布时间】:2019-11-26 22:36:16
【问题描述】:
我想在 pandas 中处理 stock level-2 数据。为简单起见,假设每行有四种数据:
- 毫秒:时间戳,int64
- last_price:最后交易价格,float64,
- ask_queue:ask端的体积,一个固定大小(200)的int32数组
- bid_queue:bid_queue的数量,一个固定大小(200)的int32数组
在 numpy 中可以很容易地定义为结构化 dtype:
dtype = np.dtype([
('millis', 'int64'),
('last_price', 'float64'),
('ask_queue', ('int32', 200)),
('bid_queue', ('int32', 200))
])
这样,我就可以访问ask_queue 和bid_queue 之类的:
In [17]: data = np.random.randint(0, 100, 1616 * 5).view(dtype)
% compute the average of ask_queue level 5 ~ 10
In [18]: data['ask_queue'][:, 5:10].mean(axis=1)
Out[18]:
array([33.2, 51. , 54.6, 53.4, 15. , 37.8, 29.6, 58.6, 32.2, 51.6, 34.4,
43.2, 58.4, 26.8, 54. , 59.4, 58.8, 38.8, 35.2, 71.2])
我的问题是如何定义一个DataFrame包含的数据?
这里有两种解决方案:
A.将ask_queue 和bid_queue 设置为两列,数组值如下:
In [5]: df = pd.DataFrame(data.tolist(), columns=data.dtype.names)
In [6]: df.dtypes
Out[6]:
millis int64
last_price float64
ask_queue object
bid_queue object
dtype: object
但是,这个解决方案至少存在两个问题:
-
ask_queue和bid_queue丢失了 2D 数组的 dtype 和所有 方便的方法; - 性能,因为它变成了对象数组而不是 2D 数组。
B.将ask_queue 和bid_quene 展平为2 * 200 列:
In [8]: ntype = np.dtype([('millis', 'int64'), ('last_price', 'float64')] +
...: [(f'{name}{i}', 'int32') for name in ['ask', 'bid'] for i in range(200)])
In [9]: df = pd.DataFrame.from_records(data.view(ntype))
In [10]: df.dtypes
Out[10]:
millis int64
last_price float64
ask0 int32
ask1 int32
ask2 int32
ask3 int32
ask4 int32
ask5 int32
...
比解决方案 A 好。但是 2 * 200 列看起来是多余的。
是否有任何解决方案可以利用 numpy 中的结构化 dtype 的优势?
我想知道ExtensionArray 或 `ExtensionDtype' 是否可以解决这个问题。
【问题讨论】:
-
pandas不是用来存储对象的。事物本质上应该组织为 2D 数组(毕竟它是为 PANel DATA 设计的)。您基本上失去了对象类型的所有有用功能。第二个选项是最好的。您可以使用df.loc[:, 'ask5':'ask9'].mean(1)计算相同的精确平均值,这与 IMO 的 numpy 功能一样简单。 -
@Eastsun:我刚刚阅读了有关 ExtensionDtype 的信息。听起来您可以将它用于您的目的,但我认为您应该仔细检查您是否也可以实现新类型所需的操作。例如,您在数组切片上的平均值。如果这不可能,您总是必须使用
map之类的方法,并且可能将结构复制到另一个 numpy 表示中以便能够执行它。这可能会使其非常缓慢。另一方面,如果您在 ExtensionDtype 中实现您的 api,那么新版本的 pandas 可能会破坏该实现,因为它是实验性的。 -
@jottbe 我刚刚找到并阅读了这个博客:tomaugspurger.github.io/pandas-extension-arrays.html,这个博客中提到的方法似乎也应该解决我的问题。稍后我会深入研究。
-
也许this anwser 可以提供帮助。最好的!
标签: python pandas numpy quantitative-finance trading