【问题标题】:Fast numpy array structure for appending and creation of pandas dataframe用于追加和创建 pandas 数据帧的快速 numpy 数组结构
【发布时间】:2018-07-29 18:34:30
【问题描述】:

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

#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)?

非常感谢!

【问题讨论】:

标签: python pandas numpy multiprocessing time-series


【解决方案1】:

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

不知道为什么reshape 需要numpy 数组:

# 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

【讨论】:

  • 谢谢!问题是我被困在一个 numpy 数组上,因为我计划通过 posix 共享内存 (gitlab.com/tenzing/shared-array) 在多个进程之间快速读写。由于 multiprocess.basemanager 和类 dict/ 列表设置太慢,我一直在寻找一个快速的 python 共享内存解决方案。
  • @trbck,我明白了。不幸的是,我不知道如何提高 numpy 附加性能。将保持我的答案,以免其他人落入陷阱。
  • 我的意思是通过 vstack “追加”是相当快的。但是需要重塑 np.array 以使用 pd.DataFrame(a.reshape((1,-1))[0]) 创建一个数据帧,这大大减慢了它的速度。我还想知道是否可以更改 np.array 的结构以更快地在此处创建数据框,因为 dtypes(因此 df 不需要进一步的处理/计算)已经在 np.array 中正确设置。
  • @trbck,我添加了一个示例。我不知道为什么reshape 是必要的
猜你喜欢
  • 2016-01-28
  • 2018-12-31
  • 2016-04-28
  • 2023-03-10
  • 2013-08-06
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多