【问题标题】:Problem with python memory, flush, csv sizepython内存,刷新,csv大小问题
【发布时间】:2019-04-17 13:03:24
【问题描述】:

在解决了数据集的排序后,我的代码出现了问题。

with open(fns_land[xx]) as infile:
    lines = infile.readlines()
    for line in lines:
        result_station.append(line.split(',')[0])
        result_date.append(line.split(',')[1])
        result_metar.append(line.split(',')[-1])

我的线路有问题。在这一行中,数据有时会很大,我得到一个终止错误。

有没有一种简短/好方法来重写这一点?

【问题讨论】:

标签: python arrays memory flush


【解决方案1】:

改用readline,这样一次读取一行而不会将整个文件加载到内存中。

with open(fns_land[xx]) as infile:
    while True:
        line = infile.readline()
        if not line:
            break
        result_station.append(line.split(',')[0])
        result_date.append(line.split(',')[1])
        result_metar.append(line.split(',')[-1])

【讨论】:

    【解决方案2】:

    如果您正在处理数据集,我建议您查看pandas,我非常适合处理数据争论。

    如果您的问题是大型数据集,您可以分块加载数据。

    import pandas as pd
    tfr = pd.read_csv('fns_land{0}.csv'.format(xx), iterator=True, chunksize=1000)
    
    1. 行:进口熊猫模块
    2. 行:以 1000 行为单位从 csv 文件中读取数据。

    这将是 pandas.io.parsers.TextFileReader 类型。要加载整个 csv 文件,请执行以下操作:

    df = pd.concat(tfr, ignore_index=True)
    

    添加参数ignore_index=True是为了避免索引重复。

    您现在已将所有数据加载到数据框中。然后将列上的数据作为向量进行处理,这也比常规的逐行更快。

    看看这里question,它处理了类似的事情。

    【讨论】:

    • 谢谢。但对我来说,使用开放方法是最好的方法。我只想读取 1000 列中的 3 列。下次使用 pandas 可能会更好。
    猜你喜欢
    • 2011-10-24
    • 2016-01-17
    • 2012-06-28
    • 2011-02-01
    • 2012-10-06
    • 2017-02-06
    • 2019-03-19
    • 2012-01-23
    • 2012-05-29
    相关资源
    最近更新 更多