繁体   English   中英

为什么我的python DataFrame性能这么慢

[英]Why is my python DataFrame performing so slowly

我正在构建一个应用程序,它可以对大型数据集进行一些非常简单的分析。 这些数据集以1000万行以上,约30列的CSV文件格式提供。 (我不需要很多列。)

逻辑告诉我,整个文件放入一个DataFrame中应该可以使其访问更快。 但是我的电脑说不。

我尝试过分批加载,以及加载整个文件,然后分批执行功能。

但是最终结果是,执行同一过程所需的时间比使用简单的文件读取选项要多十倍。

这是DataFrame版本:

def runProcess():
    global batchSize
    batchCount = 10
    if rowLimit < 0:
        with open(df_srcString) as f:
            rowCount = sum(1 for line in f)
        if batchSize < 0:
            batchSize = batchSize * -1
            runProc = readFileDf
        else:
            runProc = readFileDfBatch
        batchCount = int(rowCount / batchSize) + 1
    else:
        batchCount = int(rowLimit / batchSize) + 1
    for i in range(batchCount):
        result = runProc(batchSize, i)
        print(result)

def readFileDfBatch(batch, batchNo):
    sCount = 0
    lCount = 0
    jobStartTime = datetime.datetime.now()
    eof = False
    totalRowCount = 0

    startRow = batch * batchNo
    df_wf = pd.read_csv(df_srcString, sep='|', header=None, names=df_fldHeads.split(','), usecols=df_cols, dtype=str, nrows=batch, skiprows=startRow)
    for index, row in df_wf.iterrows():
        result = parseDfRow(row)
        totalRowCount = totalRowCount + 1
        if result == 1:
            sCount = sCount + 1
        elif result == 2:
            lCount = lCount + 1
    eof = batch > len(df_wf)
    if rowLimit >= 0:
        eof = (batch * batchNo >= rowLimit)
    jobEndTime = datetime.datetime.now()
    runTime = jobEndTime - jobStartTime
    return [batchNo, sCount, lCount, totalRowCount, runTime]

def parseDfRow(row):
#df_cols = ['ColumnA','ColumnB','ColumnC','ColumnD','ColumnE','ColumnF']
    status = 0
    s2 = getDate(row['ColumnB'])
    l2 = getDate(row['ColumnD'])
    gDate = datetime.date(1970,1,1)
    r1 = datetime.date(int(row['ColumnE'][1:5]),12,31)
    r2 = row['ColumnF']
    if len(r2) > 1:
        lastSeen = getLastDate(r2)
    else:
        lastSeen = r1
    status = False
    if s2 > lastSeen:
        status = 1
    elif l2 > lastSeen:
        status = 2
    return status

这是简单的文件阅读器版本:

def readFileStd(rows, batch):
    print("Starting read: ")
    batchNo = 1
    global targetFile
    global totalCount
    global sCount
    global lCount
    targetFile = open(df_srcString, "r")
    eof = False
    while not eof:
        batchStartTime = datetime.datetime.now()
        eof = readBatch(batch)
        batchEndTime = datetime.datetime.now()
        runTime = batchEndTime - batchStartTime
        if rows > 0 and totalCount >= rows: break
        batchNo = batchNo + 1
    targetFile.close()
    return [batchNo, sCount, lCount, totalCount, runTime]

def readBatch(batch):
    global targetFile
    global totalCount
    rowNo = 1
    rowStr = targetFile.readline()
    while rowStr:
        parseRow(rowStr)
        totalCount = totalCount + 1
        if rowNo == batch: 
            return False
        rowStr = targetFile.readline()
        rowNo = rowNo + 1
    return True

    def parseRow(rowData):
    rd = rowData.split('|')
    s2 = getDate(rd[3])
    l2 = getDate(rd[5])
    gDate = datetime.date(1970,1,1)
    r1 = datetime.date(int(rd[23][1:5]),12,31)
    r2 = rd[24]
    if len(r2) > 1:
        lastSeen = getLastDate(r2)
    else:
        lastSeen = r1
    status = False
    if s2 > lastSeen:
        global sCount
        sCount = sCount + 1
        status = True
        gDate = s2
    elif l2 > lastSeen:
        global lCount
        lCount = lCount + 1
        gDate = s2

难道我做错了什么?

iterrows没有利用向量化运算的优势。 使用pandas大多数好处来自矢量化和并行操作。

df_wf.apply(something, axis=1)替换for index, row in df_wf.iterrows():其中something是一个函数,该函数封装了iterrows所需的逻辑,并使用了numpy向量化操作。

另外,如果您的df无法容纳在内存中,因此您需要批量读取,请考虑使用daskspark覆盖pandas

进一步阅读: https : //pandas.pydata.org/pandas-docs/stable/enhancingperf.html

关于您的代码的一些注释:

  • 所有这些global变量都吓到我了! 传递参数和返回状态有什么问题?
  • 您没有使用Pandas任何功能,创建一个数据框只是为了用它对行进行愚蠢的迭代会导致它做很多不必要的工作
  • 如果这确实是最好的方法,则标准的csv模块(可以与delimiter='|' )提供了更紧密的接口

对于https://codereview.stackexchange.com/,这可能是一个更好的问题

只是发挥着替代行方式的性能。 从下面获得的收获似乎是,熊猫的“行明智”工作通常总是很慢

首先创建一个数据框进行测试:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(1, 1e6, (10_000, 2)))
df[1] = df[1].apply(str)

这需要3.65毫秒来创建带有intstr列的数据帧。 接下来,我尝试iterrows方法:

tot = 0
for i, row in df.iterrows():
    tot += row[0] / 1e5 < len(row[1])

聚合是相当愚蠢的,我只想要一些同时使用两列的东西。 耗时长达903ms。 接下来,我尝试手动进行迭代:

tot = 0
for i in range(df.shape[0]):
    tot += df.loc[i, 0] / 1e5 < len(df.loc[i, 1])

减少到408毫秒。 接下来我尝试apply

def fn(row):
    return row[0] / 1e5 < len(row[1])

sum(df.apply(fn, axis=1))

与368毫秒基本相同。 终于,我找到了熊猫满意的一些代码:

sum(df[0] / 1e5 < df[1].apply(len))

这需要4.15毫秒。 我想到的另一种方法是:

tot = 0
for a, b in zip(df[0], df[1]):
    tot += a / 1e5 < len(b)

这需要2.78毫秒。 而另一个变体:

tot = 0
for a, b in zip(df[0] / 1e5, df[1]):
    tot += a < len(b)

需要2.29毫秒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM