python - 如何制作一个迭代超过 1500 万条记录的 for 循环,节省空间?

标签 python python-3.x for-loop space-complexity

我对简单的 for 循环有疑问。我正在尝试从列表(即移动窗口列表)中计算最大值,创建这些最大值的列表,稍后我会将其添加到数据框中。

我的数据框有两列浮点值和日期时间索引。数据文件有大约 1500 万行(即我要迭代的系列的长度是 1500 万)(700 MB)。

当我在一段时间后运行我的简单循环时,我的计算机内存不足并崩溃。我有 12 GB 的内存。

我的代码:

import pandas as pd
import numpy as np

# sample data
speed = np.random.uniform(0,25,15000000)

data_dict = {'speed': speed}
df = pd.DataFrame(data_dict)

# create a list of 'windows', i.e. subseries of the list 
def GetShiftingWindows(thelist, size):
    return [ thelist[x:x+size] for x in range( len(thelist) - size + 1 ) ]

window_size = 10

list_of_win_speeds = GetShiftingWindows(df.speed, window_size)

list_of_max_speeds = []

for x in list_of_win_speeds: 
    max_value = max(x)
    list_of_max_speeds.append(max_value)

我不是CS专业的。在我看来,这像是一个空间复杂性问题。为了使计算可行,我在这里缺少什么?

最佳答案

作为第一步,我会改变

return [ thelist[x:x+size] for x in range( len(thelist) - size + 1 ) ]

进入

return ( thelist[x:x+size] for x in range( len(thelist) - size + 1 ) )

然后你将得到一个生成器,你的代码在内存中创建整个子列表列表,生成器方法将在每次 for 迭代中只生成一个子列表

如果您使用 Python 2,您还可以将 range(一次生成整个列表)更改为 xrange(生成器每次调用只生成一个值)

最后,您可以使用 islice 返回一个迭代器生成器:

from itertools import islice

return ( islice(thelist, x, x + size) for x in range( len(thelist) - size + 1 ) )

关于python - 如何制作一个迭代超过 1500 万条记录的 for 循环,节省空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42898029/

相关文章:

python - python 中的强数字

python-3.x - 无法成功比较两个字符串

python - 修复索引错误 : List out of range issues

css - 在 SASS 中创建一个集合(数组)用于@for 循环

java - Apache POI 获取 NPE 读取 xls 文件

python - 矢量化 numpy : check if point is inside sphere?

python - Pandas:如何通过拆分从一个多索引级别向多索引添加一个级别?

python - 用于查找用户最喜欢的故事的良好数据模型

python-3.x - Python浮点精度和

c++ - for循环的增量语句中的奇数位运算符