提问者:小点点

熊猫:如何获取目录中每个文件的行数的数据帧?


我有。csv文件(abc.csv,def.csv等。。) 在目录中,我想计数每一个文件中的行,并保存有名称列和计数列的单个文件。 我的预期输出如下:

df = name  count
     abc   ....
     def   ....
     ghi   ....

我正在做一些像下面这样的事情来获得计数,但不能在数据帧中隐蔽。 请建议。

import os
path = '/some/path/to/file'
for filename in os.listdir(path):
with open(filename, 'r', encoding="latin-1") as fileObj:
    # -1 to exclude the header
    print("Rows Counted {} in the csv {}:".format(len(fileObj.readlines()) - 1, filename))

共2个答案

匿名用户

将每个文件的名称/行计数放入列表中,然后在循环结束后创建数据框架:

import os

import pandas as pd

path = '/some/path/to/file'
names, counts = [], []

for filename in os.listdir(path):
    with open(filename, 'r', encoding="latin-1") as fileObj:
        names.append(filename)
        # -1 to exclude the header
        counts.append(len(fileObj.readlines()) - 1)

df = pd.DataFrame({'name': names, 'count': counts})

匿名用户

使用pandas和pathlib

from pathlib import Path
import pandas as pd

path_to_csv = 'your\\dir'

file_info = pd.DataFrame( {file.name : 
      pd.read_csv(file).shape for file in Path(path_to_csv).glob('*.csv')})\
      .T.rename(columns={0 : 'rows', 1 : 'columns'})

print(file_info)

              rows  columns
01_02_20.csv     3        3
01_28_20.csv     3        4
12_02_19.csv    77       10
12_09_19.csv    86        7