首页 > 解决方案 > 如何处理文件中的字符串和整数?

问题描述

我有一个包含姓名、学生所在年级以及学生在考试中获得的分数的文本文件。它是这种格式:

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”可能出现在测试分数中,而不仅仅是作为年级水平。我确信有更简单的方法可以做到这一点。提前感谢您的帮助!

标签: python

解决方案


正如建议的那样,这可以使用 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

推荐阅读