简体   繁体   中英

Python | how do i make a program that calculates math

I'm trying to create a code with Python 3 to import text files to python, converting it to lists and then calculate something with it like average marks.

Text file:

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

If you are happy to use a 3rd party library, you can use Pandas. With this method "conversion to lists" is not required, as data is held more efficiently in NumPy arrays.

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}')

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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