【问题标题】:python/numpy/pandas fastest way apply algorithm for expanding calculationspython/numpy/pandas 最快的方式应用算法来扩展计算
【发布时间】:2015-02-12 06:38:52
【问题描述】:

假设我有从 2000 年 1 月 1 日到 2011 年 1 月 1 日的时间序列,并且对于每个日期,我都有一些浮点值..这是在 pandas 数据框中。

我想执行一些计算。假设 N 是数据点的数量,i 是当前数据点。伪代码:

for i in n:
        some_calc(V0:Vi) + some_calc(Vi:Vn)

我可以轻松实现此计算,但看到我认为大型集合的性能问题。我认为部分原因是由于数据容器是 Dataframe,切片会创建新系列,并且在 some_calc 中,会发生更多切片。

什么是做类似事情的有效方法?我可以通过使用 numpy 来避免循环吗?

【问题讨论】:

  • 您可以尝试将所有数据放入数据框中,并使用dataframe.apply 进行逐行转换。这将避免for loop
  • 有些计算可以向量化,有些则不能。这个问题不能笼统地回答。但是,在 numpy 和 pandas 中,切片不会创建一个全新的数组,只会创建原始数据的新视图。

标签: python numpy pandas scipy


【解决方案1】:

您可以使用以下代码来提高您的代码性能:

result = []
for item in item_list:
    new_item = do_something_with(item)
    result.append(new_item)

请看下面的例子:

# finding the max prior to the current item
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = []
current_max = 0
for i in a:
    current_max = max(i, current_max)
    results.append(current_max)
# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多