简体   繁体   English

CSV Python中的文件处理和计算值

[英]CSV File Handling in Python and calculating values

I am taking an introductory course in Python and am currently discovering how to handle files using Python. I have a CSV file with a few student names, their majors and GPAs我正在 Python 上一门入门课程,目前正在探索如何使用 Python 处理文件。我有一个 CSV 文件,其中包含一些学生姓名、他们的专业和 GPA
I am trying to handle the file on python to calculate and print the average of the GPAs我正在尝试处理 python 上的文件以计算和打印 GPA 的平均值
This is a snippet of the csv file:这是 csv 文件的片段:

Ahmed Yousry,2.99,Accounting
Amina Hamdy,2.45,Marketing
Hala Hossam,3.85,BIS
Dina Gamal,3.96,BIS
Amr Nabil,3.6,Finance

and this is the code I was trying to write:这是我试图编写的代码:

import csv
f1 = open("myText.csv")
rowlist = csv.reader(f1)
sum = 0
for row in rowlist:
    sum += row[1]
avg = sum / 5
f1.close()
print("Average GPA is", avg)

However, I keep getting an error that the sum cannot be calculated since it is reading the GPA values as strings not integer values and I have no idea how to convert them但是,我一直收到无法计算总和的错误消息,因为它正在将 GPA 值读取为字符串而不是 integer 值,我不知道如何转换它们
here is what the error message says:这是错误消息的内容:

Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\practicefiles\program12.py", line 6, in <module>
    sum += row[1]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

could someone tell me where I'm going wrong?有人可以告诉我哪里出错了吗? I've tried casting the value as an int and it still won't work and I don't know what else could be done我已经尝试将值转换为 int,但它仍然无法正常工作,我不知道还能做什么
Thank you in advance to those who help out先谢谢帮忙的人

Use float() function to convert string to float type.使用float() function 将string转为float类型。

Try:尝试:

import csv

f1 = open("myText.csv")
rowlist = csv.reader(f1)
sum = 0
for row in rowlist:
    sum += float(row[1])
avg = sum / 5
f1.close()
print("Average GPA is", avg)

You can also use the pandas library to import data then calculate the average using mean() function. Once data is in a data frame, you can do a lot with it using pandas.您还可以使用pandas库导入数据,然后使用 mean() function 计算平均值。一旦数据位于数据框中,您可以使用 pandas 对其进行很多操作。

import pandas as pd

df = pd.read_csv("myText.csv", names=['name', 'GPA', 'Major'])
print("Average GPA is", df["GPA"].mean())

Output: Output:

Average GPA is 3.37

A more concise and arguably more Pythonic approach could be:一种更简洁且可以说更 Pythonic 的方法可能是:

import csv

with open('myText.csv') as csv_:
    gpas = [float(gpa) for _, gpa, _ in csv.reader(csv_)]
    print(f'Average GPA is {sum(gpas)/len(gpas):.2f}')

Note:笔记:

This will fail if the file is empty or does not conform to the example shown in the original question如果文件为空或不符合原始问题中显示的示例,这将失败

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

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