簡體   English   中英

使用python熊貓進行大文件分析的延遲

[英]Latency in large file analysis with python pandas

我有一個非常大的文件(10 GB),大約有4000億行,它是一個具有4個字段的csv。 在此說明中,第一個字段是ID,第二個字段是ID的當前位置,第三個字段是分配給該行的相關數字。 與此類似:

41545496|4154|1
10546767|2791|2
15049399|491|3
38029772|491|4
15049399|1034|5

我的意圖是在另一個文件或相同文件中創建第四列(舊位置),用於存儲您的ID的先前位置,我要做的是驗證ID號是否已經出現過,我在尋找它上次出場並分配給他的舊職位領域,即他上次出場時的職位。 如果該ID之前未出現過,那么我會將其在同一行中的當前位置分配給它的舊位置。 像這樣:

41545496|4154|1|4154
10546767|2791|2|2791
15049399|491|3|491
38029772|491|4|491
15049399|1034|5|491

我創建了一個程序來執行文件的讀取和分析,但是每分鍾執行一萬行的讀取,因此它給我提供了非常高的時間來讀取整個文件,大約需要5天以上的時間。

import pandas as pd

with open('file_in.csv', 'rb') as inf:
    df = pd.read_csv(inf, sep='|', header=None)

cont = 0
df[3] = 0

def test(x):
    global cont

    a = df.iloc[:cont,0]

    try:
        index = a[a == df[0][cont]].index[-1]
        df[3][cont] = df[1][index] 
    except IndexError:
        df[3][cont] = df[1][cont]
        pass
    cont+= 1

df.apply(test, axis=1)

df.to_csv('file_out.csv', sep='|', index=False, header=False)

我在大學里有一台64位處理器和64 GB RAM的計算機,但是仍然很長一段時間,有什么辦法可以減少時間? 非常感謝你!

有效處理數據

您的方法存在兩個主要問題:

  • 那樣的數據量應該永遠不會被寫入文本文件
  • 您的方法需要(n ^ 2/2)個比較

一個更好的主意是在進行實際工作之前首先對數組進行索引排序。 因此,在最壞的情況下,您只需要大約2n個操作即可進行比較,而n * log(n)個操作則可以進行排序。

我還使用了numba來編譯該函數,它將使計算時間加快100倍或更多。

import numpy as np

#the hardest thing to do efficiently
data = np.genfromtxt('Test.csv', delimiter='|',dtype=np.int64)

#it is important that we use a stable sort algorithm here
idx_1=np.argsort(data[:,0],kind='mergesort')
column_4=last_IDs(data,idx_1)

#This function isn't very hard to vectorize, but I expect better
#peformance and easier understanding when doing it in this way
import numba as nb
@nb.njit()
def last_IDs(data,idx_1):
  #I assume that all values in the second column are positive
  res=np.zeros(data.shape[0],dtype=np.int64) -1
  for i in range(1,data.shape[0]):
    if (data[idx_1[i],0]==data[idx_1[i-1],0]):
      res[idx_1[i]]=data[idx_1[i-1],1]

  same_ID=res==-1
  res[same_ID]=data[same_ID,1]

  return res

有關高性能寫入和讀取數據的信息,請訪問: https : //stackoverflow.com/a/48997927/4045774

如果您沒有獲得至少100 M / s的IO速度,請詢問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM