【问题标题】:Sum Each Column of CSV file对 CSV 文件的每一列求和
【发布时间】:2020-01-28 17:50:34
【问题描述】:

我有一个包含 32 个列标题的大型 CSV 文件。我想总结每一列,结果是每个列标题的 32 个单独的总和。我可以访问 python 和 powershell。任何帮助将不胜感激。

我得到的最远的是这个网站:pandas groupby with sum() on large csv file?

【问题讨论】:

  • 导入到 excel 中然后在那里做?它不是程序化的,但如果您只需要执行一次,它可能是最快的方式。
  • 文件超过 1GB。无法加载到 Excel 中。
  • 只需使用简单的for 循环,就不需要将整个文件读入内存。
  • 我的意思是我对python非常缺乏经验,并且不确定如何执行链接中提供的方法。我不确定如何跳过“groupby”部分。
  • @specmer:因此,如果您还没有使用 python 的经验,我下面的回答应该可以帮助您开始。没有导入没有框架,您可以轻松地消化一千兆字节的数据,如您所描述的 ;-) 我们都开始缺乏经验,并且知道这是我们有时会忘记的力量......

标签: python powershell


【解决方案1】:
import pandas as pd
pd.read_csv(r'my_path_to_file/my_file.csv', sep=';').sum().values

Pandas 绝对是必经之路。这两行代码将打印出列的总和。如果您在 Windows 上,请使用“\”来指定您的路径。我假设您的 csv 文件使用分号作为分隔符(如果它是逗号,则使用 sep=',' 如果它是制表符,则使用 sep='\t')

如果要将结果写入文件,请使用:

import pandas as pd
df = pd.read_csv(r'my_path_to_file/my_file.csv', sep=';').sum()
df.to_csv(r'my_path_to_file/my_file_sum.csv')

【讨论】:

  • 所以我几乎把一些东西放在一起,这就是我最好的结果:$ ipython In [1]: import dask.dataframe as dd In [2]: df = dd.read_csv('so.csv', sep=',') In [3]: df.head() Out [3]: In [5]: df.sum().compute() Out[5]:
  • Vincent Claes 和我的代码的不同之处在于我的代码包含了标题。
  • @specmer 如果您想包含标头,只需运行代码以保存到文件中。在此文件中,您将看到具有相应值的列名。
【解决方案2】:

在 powershell(或 Linux/Mac OS 等)中,您应该能够安装出色的 CSVFIX 命令行包(它在大型 CSV 文件上运行速度非常快,并且还有一个 Windows 安装程序)。

您可以使用 CSVFIX summary 命令生成每列的总和:

csvfix summary -sum 1:32 filename.csv

这将为您提供每列总和的单行摘要:

"43", "21", "425", "1092", [...]

如果文件有标题行,别忘了添加-ifn 标志以忽略第一行。

【讨论】:

    【解决方案3】:

    您可以在 pandas 中使用read_csv 读取文件,然后在数据帧上使用sum()

    import pandas as pd
    
    filename = r'folder/file.txt'
    df = pd.read_csv(filename)
    total = df.sum()
    

    【讨论】:

    • 所以是这样的:df.sum().compute()
    • 我做错了什么? In [1]: import pandas as pd In [2]: filename = r'C:\Temp\Symphony\output.csv' In [3]: df = pd.read_csv(r) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-3-8dcaa1f867a7> in <module>() ----> 1 df = pd.read_csv(r) NameError: name 'r' is not defined In [4]: df = pd.read_csv('C:\Temp\Symphony\output.csv') In [5]: total = df.sum() In [6]:
    • df = pd.read_csv(r) 应该是df = pd.read_csv(filename)
    • 啊。明白了。一旦我输入total = df.sum() 我没有得到任何输出
    • total 是熊猫系列。试试print(total)。或Total['A'],其中“A”是列名。
    【解决方案4】:

    在此示例数据文件上仅使用内置函数的简单方法:

    #! /usr/bin/env python
    from __future__ import print_function
    
    sep = ';'
    with open('32_numeric_columns.csv', 'rt') as f:
        columns = f.readline().strip().split(sep)
        rows = [0] * len(columns)
        for line in f.readlines():
            data = line.strip().split(sep)
            for i, cell in enumerate(data, start=0):
                rows[i] += float(cell)
    
    
    print(columns)
    print(rows)
    

    在这个数据文件上:

    a0;a1;a2;a3;a4;a5;a6;a7;a8;a9;b0;b1;b2;b3;b4;b5;b6;b7;b8;b9;c0;c1;c2;c3;c4;c5;c6;c7;c8;c9;d0;d1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1;1
    

    产量:

    ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'd0', 'd1']
    [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0]
    

    处理一个包含 1280000000 字节数据的大文件大约需要花费在我的机器上生产 5 分钟:

    $> time ./so_csv_adder.py
    ['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'd0', 'd1']
    [20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0, 20000000.0]
    
    real    4m47.374s
    user    4m43.748s
    sys 0m2.545s
    

    【讨论】:

      【解决方案5】:
      import csv
      with open('yourBigFile.csv', 'rb') as f:
          spreadsheet=csv.reader(f) #you may need some options 
                                    #depending on the format of the file
          header=None
          for row in spreadsheet:
              if header is None:
                  header=row
                  mySums=[0]*len(row) #  initialize to zero
                  continue
              else:
                  # this will only work if every cell has a number
                  #   this will be faster, so use it if it is possible
                  #   in your application
                  #mySums=[mySums[x]+float(row[x]) for x in range(len(mySums))]
      
                  # more generally
                  for i,x in enumerate(row):
                      try:
                          converted=float(x)
                      except ValueError:   #you may actually want an error
                                           #raised.  YMMV depending on your data
                          converted=0
                      mySums[i]+=converted
      

      由于我不确定您希望如何格式化输出,所以我将把它留给您。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多