简体   繁体   English

对CSV文件的每一列求和

[英]Sum Each Column of CSV file

I have a large CSV file with 32 column headers.我有一个包含 32 个列标题的大型 CSV 文件。 I'd like to sum up each column and the result be 32 individual summations of each column header.我想总结每一列,结果是每个列标题的 32 个单独的总和。 I have access to both python and powershell.我可以访问 python 和 powershell。 Any help would be appreciated.任何帮助将不胜感激。

The furthest I got was this site: pandas groupby with sum() on large csv file?我得到的最远的是这个站点: pandas groupby with sum() on large csv file?

In powershell (or Linux/Mac OS etc) you should be able to install the excellent CSVFIX command-line package (which works very fast on large CSV files and also has a Windows installer).在 powershell(或 Linux/Mac OS 等)中,您应该能够安装出色的CSVFIX命令行包(它在大型 CSV 文件上运行速度非常快,并且还具有 Windows 安装程序)。

You can use the CSVFIX summary command to generate a sum of each column:您可以使用 CSVFIX summary命令生成每列的总和:

csvfix summary -sum 1:32 filename.csv

This will give you a single-line summary of the sum of each column:这将为您提供每列总和的单行摘要:

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

If the file has a header row don't forget to also add the -ifn flag to ignore the first row.如果文件有标题行,请不要忘记添加-ifn标志以忽略第一行。

You can use read_csv in pandas to read the file, and then just use sum() on the dataframe.您可以在read_csv中使用read_csv来读取文件,然后在数据帧上使用sum()

import pandas as pd

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

A simple way using only builtins on this sample data file:仅在此示例数据文件上使用内置函数的简单方法:

#! /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)

on this data file:在这个数据文件上:

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

yields:产量:

['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]

Working on a huge file with 1280000000 bytes of data took approx.处理一个包含 1280000000 字节数据的大文件需要大约。 5 minutes on my machine to produce:在我的机器上生产 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
import pandas as pd
pd.read_csv(r'my_path_to_file/my_file.csv', sep=';').sum().values

Pandas is definitly the way to go .熊猫绝对是要走的路。 these two lines of code will print out the sum of the columns.这两行代码将打印出列的总和。 if you are on windows use a '\\' for specifying your path.如果您在 Windows 上,请使用“\\”来指定您的路径。 I assume your csv file uses a semicolon as a seperator (if its a comma use sep=',' if its a tab use sep='\\t')我假设您的 csv 文件使用分号作为分隔符(如果它是逗号,请使用 sep=',如果它是制表符,请使用 sep='\\t')

If you want to write the result to a file use:如果要将结果写入文件,请使用:

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')
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

As I am not sure how you want the output to be formatted, I will leave that to you.由于我不确定您希望如何格式化输出,因此我将把它留给您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM