Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中的CSV文件中添加行_Python_Csv - Fatal编程技术网

在python中的CSV文件中添加行

在python中的CSV文件中添加行,python,csv,Python,Csv,CSV文件的示例: def sumRows(filename, header=False): d = {} total = 0 with open ('{0}'.format(filename)) as csvfile: rdr = csv.reader(csvfile) for row in rdr: if(header==True): rdr.next() # skips first row if header

CSV文件的示例:

def sumRows(filename, header=False):
d = {}
total = 0
with open ('{0}'.format(filename)) as csvfile:
    rdr = csv.reader(csvfile)
    for row in rdr:
        if(header==True):
            rdr.next() 
            # skips first row if header is set to true
            continue
            total = ? 
            # function I do not know how to do
            d[row[0]] = total
print(d)

我需要它来添加行,比如,对于bob,它应该是15+4+4,tim,它应该是29+0,它应该忽略任何空格,有人知道我如何在Python3中做到这一点吗?它应该以字典的形式打印

如果您可以使用pandas,您可以简单地按如下方式执行:

bob    15   4   4
tim    29       0
anna   18       9

另请注意,读取csv时默认使用“,”作为分隔符。要更改分隔符,可以使用
sep
参数。

您需要将文本单元格转换为一个数字,忽略空白单元格,然后对它们求和

import pandas as pd
df  = pd.read_csv('data.csv', header=None).set_index(0)
print(df.sum(axis = 1))
顺便说一下,您还应该将处理标头的代码移动到循环之前;否则,它将在循环的每一次迭代中运行这个

def sum_rows(filename, header=False):
    d = {}
    with open(filename) as csvfile:
        rdr = csv.reader(csvfile, delimiter='\t')
        if header:
            rdr.next()
        for row in rdr:
            d[row[0]] = sum(int(s) for s in row[1:] if s.strip() != '')
    return d