如何从标记化的txt文件添加和打印数字

时间:2019-02-05 14:29:46

标签: python-3.x math text sum multiple-columns

import csv

csv_file = 'Annual Budget.csv'
txt_file = 'annual_budget.txt'
with open(txt_file, 'w') as my_output_file:
with open(csv_file, 'r') as my_input_file:
    reader = csv.reader(my_input_file)
    for row in reader:
        my_output_file.write(" ".join(row)+'\n')
        data = []

with open(r'annual_budget.txt', 'r') as f:
 reader = csv.reader(f)
 header = next(reader) # this will yield first row i.e columns
 for line in reader:
     rowdata = map(float, line)
     data.extend(rowdata)
 print(sum(data)/len(data))

我正在尝试将CS​​V文件中的列总和打印为txt文件。我告诉我的代码绕过第一行之后,我首先逐步标记了csv文件。我的文件中的字符串标题)会引发错误,提示它无法将字符串转换为浮点数。

输出:

data.extend(rowdata) ValueError: could not convert string to float:

1 个答案:

答案 0 :(得分:0)

让它作为示例csv文件:

enter image description here

将其另存为example.csv

读取csv文件:

import pandas as pd   
df=pd.read_csv('example.csv',header=None)

将每一列的数据放入一个numpy数组中,并打印每一列的总和,同时在文件的各列上进行迭代:

import numpy as np
for x in range(len(df.columns)):
    columndata=np.asarray(df[x])
    print(sum(columndata))

您将获得输出:

  

12.2 12 23 21