2014-02-28 146 views
0

我有這樣計算的迭代

代碼巨大的CSV文件熊貓據幀平均,持續時間

101,32

205,111

722,33

205,67

722,33

205,241

現在我正在閱讀chunk文件,因爲文件非常大。如何計算每個代碼的平均持續時間並將其保存到CSV文件?

感謝

回答

1

您可以通過代碼組和存儲的數量和'Code''Duration'總和;是這樣的:

import pandas as pd 

def f(g): 
    return pd.DataFrame({'count': [g.shape[0]], 'sum': [g['Duration'].sum()]}) 

reader = pd.read_csv('data.csv',chunksize=2) 
acc = pd.DataFrame({}) 
for chunk in reader: 
    acc = acc.add(chunk.groupby('Code').apply(f).reset_index(level=1,drop=True),fill_value=0) 

acc['avg'] = acc['sum']/acc['count'] 
print acc 

acc.to_csv('avg_codes.csv',cols=['avg'],index_label='Code') 

輸出端子:

 count sum   avg 
Code       
101  1 32 32.000000 
205  3 419 139.666667 
722  2 66 33.000000 

文件avg_codes.csv輸出:

Code,avg 
101,32.0 
205,139.66666666666666 
722,33.0 
+0

我得到異常 類型錯誤:不支持的操作數類型(S) for +:'float'and'str' 代碼爲 從熊貓 進口熊貓作爲PD 進口numpy的作爲NP 導入* 從numpy.random進口randn DEF F(克): 返回pd.DataFrame({ '計數':[g.shape [0]], '和':[克[ '時長']之和()。]}) 讀者= pd.read_csv( 「Sample.csv」,迭代=真,CHUNKSIZE = 1000,usecols = [1,5]) acc = pd.DataFrame({}) 用於閱讀器中的塊: acc = acc.add(chunk.groupby('To')。apply(f).reset_index(level = 1,drop = True),fill_value = 0 ) acc ['avg'] = acc ['sum']/acc ['count'] print acc – user3345896

+0

是一個問題數據。解決方案運作良好。謝謝 – user3345896

1

使用groupby.sizegroupby.sum爲每個數據幀,然後將其降低到結果:

import numpy as np 
import pandas as pd 

c = np.random.randint(100, 10000, 100000) 
d = np.random.rand(100000) 

df = pd.DataFrame({"c":c, "d":d}) 
r1 = df.groupby("c").d.mean() 

counts = [] 
sums = [] 
for i in range(10): 
    df2 = df[i*10000:(i+1)*10000] 
    g = df2.groupby("c").d 
    counts.append(g.size()) 
    sums.append(g.sum()) 

from functools import partial 
func = partial(pd.Series.add, fill_value=0) 
r2 = reduce(func, sums)/reduce(func, counts).astype(float) 

您還可以使用下面的最後一步代碼:

r3 = pd.concat(sums, axis=1).sum(axis=1)/pd.concat(counts, axis=1).sum(axis=1).astype(float) 

檢查結果:

print np.allclose(r1, r2) 
print np.allclose(r1, r3) 
1

不是pandas但它的工作原理和內存效率。

import csv 
from collections defaultdict 

code_counts = defaultdict(int) 
code_durations = defaultdict(int) 
with open('yourfile.csv', 'rb') as f: 
    reader = csv.reader(f) 
    next(reader) # discard header row 
    for code, duration in reader: 
     code_counts[code] += 1 
     code_durations[code] += int(duration)  
code_averages = {code: code_duratons[code]/float(code_counts[code]) for code in code_counts}