如何在CSV文件python中求和

2024-05-12 22:03:36 发布

您现在位置:Python中文网/ 问答频道 /正文

[在此处输入图像描述][1][在此处输入图像描述][2]我有一个包含14个类别和303行的CSV文件,我需要找到每个类别的总和。遗憾的是,到目前为止,我所掌握的知识对于如何单独和独立地找到每个类别的总和没有多大帮助 缩写的14个类别依次为年龄、gen、cpt、rbp、sc、fbs、rer、mhra、eia、sd、spsd、nmv、dt、hd

    import string
with open("train.csv", "r") as f:
    for hd in f.read ():13

前几行是这样的

A B C D E f G H I J K L M N公司

63 1 145 233 1 2 150 0 2.3 3 0 6 0

67 1 4 160 286 0 2 108 1 1.5 2 3 2

67 1 4 120 229 0 2 129 1 2.6 2 7 1


Tags: 文件csv图像类别genschdeia
3条回答

Python有一个非常有用的“csv”模块。你知道吗

import csv

with open("train.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        # work on each row as a list

还有一个方便的DictReader,它将CSV的第一行解析为行标题,然后将每一行作为字典提供给您,并为标题设置键。你知道吗

既然数据是一种易于使用的格式,那么求和应该很容易。你知道吗

您可以每一行映射到floattransposesum每一列,并使用(column\u name,column\u sum)对进行dict:

import  csv

with open("train.csv", "r") as f:
    r = csv.reader(f)
    # pull first row i.e A,B,C,D... to use ad the keys
    keys = next(r)
    # iterate ober the rows mapping to float and transpose
    # with zip(*... so rows become columns, one per key
    summed_dict = dict(zip(keys, map(sum, zip(*(map(float, row) for row in r)))))

对于您的输入示例:

A,B,C,D,E,f,G,H,I,J,K,L,M,N
63,1,1,145,233,1,2,150,0,2.3,3,0,6,0
67,1,4,160,286,0,2,108,1,1.5,2,3,3,2
67,1,4,120,229,0,2,129,1,2.6,2,2,7,1

输出:

{'K': 7.0, 'D': 425.0, 'B': 3.0, 'G': 6.0, 'f': 1.0, 'N': 3.0, 'M': 16.0, 'C': 9.0, 'A': 197.0, 'E': 748.0, 'L': 5.0, 'H': 387.0, 'I': 2.0, 'J': 6.4}

你可以使用听写器,但在这里使用它没有真正的优势。你知道吗

Numpy可能是你的朋友:

import numpy as np

# load array from csv
arr = np.loadtxt('data.csv', dtype=float, delimiter=';', skiprows=0)

n = -1
# get n-th row by fany indexing
row = arr[n,:]
print row
print np.sum(row)

m = 2
# get m-th col by fancy indexing
col = arr[:,m]
print col
print np.sum(col)

这几乎是不言自明的。更多信息:read the docs

相关问题 更多 >