Python |我如何制作一个计算数学的程序

时间:2018-09-28 12:57:43

标签: python arrays python-3.x list text-files

我正在尝试使用Python 3创建代码以导入文本文件 到python,将其转换为列表,然后用它来计算平均值之类的值。

文本文件:

number name subject1 subject2 subject3 subject4 subject5
1234567 Jun 5 7 0 6 4
3526435 Merie 5 5 7 0 0
2230431 Kaes 6 10 0 8 6
7685433 Endré 4 7 8 7 5
0364678 Ontoinette 0 2 8 8 8
1424354 Yerôme 7 9 0 5 0
4536576 Mamal 8 0 8 7 8
1256033 Eiana 0 0 0 0 0
5504657 Wetra 6 6 7 0 6
9676575 Aalika 0 6 0 0 8
0253756 Oamira 3 8 6 7 10

1 个答案:

答案 0 :(得分:3)

如果您愿意使用第三方库,则可以使用熊猫。使用此方法,由于将数据更有效地保存在NumPy数组中,因此不需要“转换为列表”。

import pandas as pd

# read input file
df = pd.read_csv('file.csv')

# calculate mean, ignoring 0 values
df['mean'] = df.iloc[:, 2:].astype(float).replace(0, np.nan).mean(1)

# iterate rows and print results
for name, mean in df.set_index('name')['mean'].items():
    print(f'{name} has average of {mean:.2f}')

输出:

Jun has average of 5.50
Merie has average of 5.67
Kaes has average of 7.50
Endré has average of 6.20
Ontoinette has average of 6.50
Yerôme has average of 7.00
Mamal has average of 7.75
Eiana has average of nan
Wetra has average of 6.25
Aalika has average of 7.00
Oamira has average of 6.80