python - 用于附加和创建 pandas 数据帧的快速 numpy 数组结构

标签 python pandas numpy multiprocessing time-series

我花了几个小时尝试想出最有效的方法来构造并将流动的刻度数据附加到shared memory numpy 数组,然后及时获取 pandas DataFrame。

#source tick data comes in as dict
tick_data = {"bid": float(1.2), "ask": float(1.3), "time": datetime.datetime.now()}


#construct np array
dtype_conf = [('bid', '<f4'), ('ask', '<f4'), ('time', 'datetime64[us]')]
new_tick = np.array([(11.11, 22.22, now)], dtype=dtype_conf)

#append / vstack / .. it to existing shared numpy array
shared_np_array = np.vstack((shared_np_array, new_tick))

#fast construction of pd.DataFrame if needed 
pd.DataFrame(shared_np_array.reshape((1,-1))[0])

问题:

1) 构建数组并(更快)向其中添加新的刻度数据的正确方法是什么?

2)创建完整数组的 pd.DataFrame 或列的 pd.Series 最有效的方法是什么?

3)是否有更好的方法在 python 中处理共享内存时间序列(除了 multiprocessing.basemanager)?

非常感谢!

最佳答案

numpy 对于附加数据来说不是一个好的数据类型选择。

Python 中最通用的选择是 collections.deque ,它针对在列表的开头或结尾插入项目进行了优化。

您的代码可能如下所示:

import pandas as pd, numpy as np
import datetime
from collections import deque

now = datetime.datetime.now()
lst_d = deque()

#source tick data comes in as dict
tick_data = {"bid": float(1.2), "ask": float(1.3), "time": now}

#construct np array
dtype_conf = [('bid', '<f4'), ('ask', '<f4'), ('time', 'datetime64[us]')]
new_tick = np.array([(11.11, 22.22, now)], dtype=dtype_conf)

# existing deque object named lst_d
lst_d.append(list(new_tick))

# example of how your deque may look
lst_d = deque([[1, 2, 'time1'], [3, 4, 'time3'], [4, 5, 'time4']])

#fast dataframe construction
print(pd.DataFrame(list(lst_d), columns=['bid', 'ask', 'time']))

#    bid  ask   time
# 0    1    2  time1
# 1    3    4  time3
# 2    4    5  time4

不确定为什么 numpy 数组需要 reshape:

# example of how your deque may look
lst_d = np.array([[1, 2, 'time1'], [3, 4, 'time3'], [4, 5, 'time4']])

#fast dataframe construction
print(pd.DataFrame(lst_d, columns=['bid', 'ask', 'time']))

#    bid  ask   time
# 0    1    2  time1
# 1    3    4  time3
# 2    4    5  time4

关于python - 用于附加和创建 pandas 数据帧的快速 numpy 数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48867620/

相关文章:

python - python中如何对二维数组进行排序

python - 提取列中的嵌套元素并存储到新列中

python - 如何在 Pandas DataFrame 中一次获取多列的值计数?

Python + NumPy : When is it useful to manually collect garbage?

python - 单个模型对象可以是多个子对象的父对象吗?

python - 使用Python通过串口发送文件

python - 我如何比较 pandas 中具有相同类别的两个日期列

python - Pandas 无法像我期望的那样工作 apply

python - Pandas DataFrame 多线程没有性能提升

python - 将所有数据框列转换为 float 的最快方法 - pandas astype slow