python - 如何处理文件中的字符串和整数?
问题描述
我有一个包含姓名、学生所在年级以及学生在考试中获得的分数的文本文件。它是这种格式:
John Doe 3 87
Jane Doe 4 89
Bob Smith 5 84
我需要找到三年级、四年级和五年级所有学生的平均值。这就是我所做的:
inFile = open("input.txt", "r", encoding = "utf8")
counter5 = 0
counter4 = 0
counter3 = 0
total5 = 0
total4 = 0
total3 = 0
for line in inFile:
if "5" in line:
total5 += int(line[-3:-1])
counter5 += 1
elif "4" in line:
total4 += int(line[-3:-1])
counter4 += 1
elif "3" in line:
total3 += int(line[-3:-1])
counter3 += 1
print(total5/counter5)
print(total4/counter4)
print(total3/counter3)
当然,问题在于,在我的 if 语句中,“3”、“4”或“5”可能出现在测试分数中,而不仅仅是作为年级水平。我确信有更简单的方法可以做到这一点。提前感谢您的帮助!
解决方案
正如建议的那样,这可以使用 pandas 来完成。
这是使用熊猫解决此问题的方法。
输入文件(input.txt):
John Doe 3 87
Jane Doe 4 89
Bob Smith 5 84
Chris Cruse5 3 85
Karen Cane4 4 93
Rob Green3 5 94
Babe Ruth4 3 78
Step Curry1 4 79
Leb James4 5 77
import pandas as pd
df = pd.read_csv('input.txt', sep=" ", header=None)
df.columns = ['First','Last','Grade','Score']
print (df)
print (df.groupby('Grade')['Score'].mean().round(2))
数据将存储到 pandas 数据框中,如下所示:
First Last Grade Score
0 John Doe 3 87
1 Jane Doe 4 89
2 Bob Smith 5 84
3 Chris Cruse5 3 85
4 Karen Cane4 4 93
5 Rob Green3 5 94
6 Babe Ruth4 3 78
7 Step Curry1 4 79
8 Leb James4 5 77
每个等级的平均值为:
Grade
3 83.33
4 87.00
5 85.00
你也可以给:
print (df.groupby('Grade').agg({'Score':['mean']}).round(2))
Score
mean
Grade
3 83.33
4 87.00
5 85.00
推荐阅读
- java - java.lang.IllegalStateException:找不到类型的阅读器:类 io.helidon.examples.quickstart.se.pokemon.Pokemon
- json - 从 txt 文件中提取特定字符串并将提取的字符串复制到批处理文件中的 json 文件中
- json - react-native + axios 中的 JSON.parse
- c# - 替换字符串内的文本
- php - 如何在 Twig 视图中使用 Codeigniter 分页?
- java - 如何获取 UaNode 的 DataType?
- python - 在 python 中解析多行 json 对象时出错
- python - 如何使用 django-rest-framework 将嵌套的 m2m 字段序列化为自身?
- laravel - 通过加入列的 JSON 对象键获取结果
- pycharm - 如何在没有 Anaconda 环境的情况下激活 pycharm 中的 Tensorboard?