python - 将 CSV 文件读取为执行加法和平均的文本文件

标签 python python-3.x csv sum average

import csv                                                          
with open('Annual_Budget.csv') as csvfile:

readCSV = csv.reader(csvfile, delimiter=',')

Column_Sum = []
Third_Column_Avg = []
High_Value = []
Low_Value = []

for row in readCSV:
   Column_Sum = []
Third_Column_Avg = []
High_Value = []
Low_Value = []

Column_Sum.append(Column_Sum)
Third_Column_Avg.append(Third_Column_Avg)
High_Value.append(High_Value)
Low_Value.append(Low_Value)

print(Column_Sum)
print(Third_Column_Avg)
print(High_Value)
print(Low_Value)`

如何将 csv 读取为文本文件,并为每一行将所有数字列相加,跳过任何不能被视为数字的列,并在完成时显示总和。它还必须在第三列中显示所有值的平均值。它还必须显示第二列中的最高值和最低值,并显示这些值出现在哪一行。我以图片格式放置了模拟年度预算,以便您可以了解我想要完成的任务。 CSV SCREENSHOT EXAMPLE 输出:[所有数字列的总和]、[第三列中所有值的平均值]、[第二列中的最高值][第二列中的最低值]

最佳答案

使用 pandas 库(我制作了一个与您的屏幕截图类似的文件),如果您没有此库,只需 pip install pandas

然后

In [1]: import pandas as pd

In [2]: my_file = pd.read_csv('stack.csv')

In [3]: my_file
Out[3]:
   anual budget    q2    q4
0            100  450    20
1            600  765    50
2            500  380    79
3            800  480   455
4           1100   65  4320

年度预算,第二季度和第四季度总和


my_file['anual budget '].sum() 
my_file['q2'].sum() 
my_file['q4'].sum() 

第三列的平均值

my_file['q4'].mean()

第二列的最小值和最大值

my_file['q2'].max()
my_file['q2'].min()

关于python - 将 CSV 文件读取为执行加法和平均的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527002/

相关文章:

python - 在 Python 中调试外部系统命令

python - 从两列随机生成唯一组合

python - 如何使用 DataFrame 中的行值作为 Pandas 中的操作列?

crash - 在python 3 idle中使用特殊字符^或¨使程序崩溃

javascript - 来自 CSV 的 d3 可缩放 TreeMap

python - 用于设置 xtics 的 mpld3 插件

html - 在使用html表单上传的Django中读取Excel文件

c++ - C++、Python 3.7.4、SWIG 4.0.0 和 Windows 10 的问题 - ModuleNotFoundError

MySQL-将列加载到与现有数据匹配的先前表中

java - 正则表达式查找 csv 中缺少的双引号