【问题标题】:How to add all count rows in multiple csv file如何在多个csv文件中添加所有计数行
【发布时间】:2021-10-25 19:57:07
【问题描述】:

我有多个 CSV 文件,想计算每个文件的所有行,但不包括标题列。结果将显示所有文件记录数和总记录数:

以下代码将统计所有带有标题列的 CSV 文件记录

import glob
import pandas as pd
files = glob.glob('Folder/*.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())

问题:如何得到以下结果: 期待结果

File1 3 无标题列行数

File2 3 无标题列行数

File3 2 无标题列行数

共 8 个

参考链接:How to count rows in multiple csv file

【问题讨论】:

    标签: python csv count


    【解决方案1】:

    你可以试试:

    import glob
    
    files = glob.glob('Folder/*.csv')
    d = {}
    total = 0
    for f in files:
        with open(f, 'r') as out:
            nb_row = len(out.readlines())
            d[f.replace(".csv", "")]= nb_row
            total += nb_row
    print(d)
    print("Total", total)
    

    【讨论】:

    • 嗨,克莱门特·佩鲁。我收到此错误“UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 3823: character maps to . We may need to change encoding?”
    【解决方案2】:

    熊猫解决方案:

    import os
    import pandas as pd
    
    path = "C:/Users/username"
    files = [file for file in os.listdir(path) if file.endswith(".csv")]
    
    output = pd.Series(name="Rows", dtype=int)
    for file in files:
        df = pd.read_csv(os.path.join(path, file))
        output.at[file.replace(".csv", "")] = df.shape[0]
    output.at["Total"] = output.sum()
    
    >>> output
    File1    3
    File2    3
    File3    2
    Total    8
    Name: Rows, dtype: int64
    

    CSV 解决方案:

    import os
    import csv
    
    path = "C:/Users/username"
    files = [file for file in os.listdir(path) if file.endswith(".csv")]
    
    output = dict()
    for file in files:
        with open(os.path.join(path, file)) as f:
            reader = csv.reader(f)
            output[file.replace(".csv", "")] = sum(1 for row in reader)-1
    output["Total"] = sum(output.values())
    
    >>> output
    {'File1': 3, 'File2': 3, 'File3': 2, 'Total': 8}
    

    【讨论】:

    • 嗨 not_speshal。您是否添加了所有文件行数的总数?我在运行您的代码时收到错误消息:“:7: DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in the future version.明确指定一个 dtype将此警告静音。输出 = pd.Series(name="Rows")"
    • @Anson - 编辑了我的答案以包括“总计”并消除警告。
    • 嗨 Not_speshal,您的解决方案很好。您可以在代码中添加打印(输出)吗?我会接受你的解决方案
    • 嗨 not_speshal,谢谢。我接受它作为解决方案!
    • @Anson - 乐于助人! :)
    猜你喜欢
    • 2017-09-05
    • 2019-12-29
    • 1970-01-01
    • 2018-10-16
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多