[英]How to count rows in multiple csv file
我有如下的csv文件
文件1
A B
1 2
3 4
文件2
A B
1 2
文件3
A B
1 2
3 4
5 6
我想計算所有csv文件中的行
我試過了
f=pd.read_csv(file1)
f.shape
但是,當我有大量的csv文件時,它會花費太多時間。
我想得到如下結果
rows
file1 2
file2 1
file3 3
我怎么能得到這個結果?
您可以創建所有文件的length
dict
,然后為DataFrame
Series
m添加to_frame
:
import glob
import pandas as pd
files = glob.glob('files/*.csv')
d = {f: sum(1 for line in open(f)) for f in files}
print (pd.Series(d))
print (pd.Series(d).rename('rows').rename_axis('filename').reset_index())
open
並不能保證文件被正確關閉,因此另一種解決方案是:
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
d = {f: file_len(f) for f in files}
為了完整起見,這里總結了有關速度和正確打開/關閉文件的所有內容,因此該解決方案可以快速運行,不需要太多代碼,...僅限於* nix系統(?) (但我認為類似的技術也可以在其他系統上使用)。
下面的代碼比rawincount()
快rawincount()
並且還對最后一行中沒有末尾'\\ n'的行進行rawincount()
有問題):
import glob, subprocess, pandas
files = glob.glob('files/*.csv')
d = {f: subprocess.getoutput("sed -n '$=' " + f) for f in files}
print(pandas.Series(d))
PS在這里,我在一些大型文本文件(39個文件,總大小為3.7 GB,Linux Mint 18.1,Python 3.6)上運行了一些計時。 令人着迷的是建議的wc -l *.csv
方法的時機:
Results of TIMING functions for getting number of lines in a file:
-----------------------------------------------------------------
getNoOfLinesInFileUsing_bash_wc : 1.04 !!! doesn't count last non empty line
getNoOfLinesInFileUsing_bash_grep : 1.59
getNoOfLinesInFileUsing_mmapWhileReadline : 2.75
getNoOfLinesInFileUsing_bash_sed : 3.42
getNoOfLinesInFileUsing_bytearrayCountLF_B : 3.90 !!! doesn't count last non empty line
getNoOfLinesInFileUsing_enumerate : 4.37
getNoOfLinesInFileUsing_forLineInFile : 4.49
getNoOfLinesInFileUsing_sum1ForLineInFile : 4.82
getNoOfLinesInFileUsing_bytearrayCountLF_A : 5.30 !!! doesn't count last non empty line
getNoOfLinesInFileUsing_lenListFileObj : 6.02
getNoOfLinesInFileUsing_bash_awk : 8.61
嘗試這個,
它為每個條目添加文件名和行數,並且列具有適當的標簽:
import os
df = pd.DataFrame(columns=('file_name', 'rows'))
for index,i in enumerate(os.listdir('.')):
df.loc[index] = [i,len(pd.read_csv(i).index)]
迄今為止,提供的解決方案在使用大型csv時並不是最快的。 另外,在列表推導中使用open()
不能保證文件正確關閉,例如with
使用with
(請參閱此問題 )。 因此,將其與這個問題的見解相結合可以提高速度:
from itertools import takewhile, repeat
def rawincount(filename):
with open(filename, 'rb') as f:
bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
return sum(buf.count(b'\n') for buf in bufgen)
並應用@jezrael提供的解決方案:
import glob
import pandas as pd
files = glob.glob('files/*.csv')
d = {f: rawincount(f) for f in files}
df = pd.Series(d).to_frame('rows')
在* nix系統中,如果可以在Python之外進行操作,請執行以下操作:
wc -l *.csv
應該做到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.