0

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
Doughnut
  • 25
  • 5

1 Answers1

3

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
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Do I have to change the file.csv to file.txt but when I try to do that it gives a error. – Doughnut Sep 28 '18 at 13:39
  • @Doughnut, See [Load data from txt with pandas](https://stackoverflow.com/questions/21546739/load-data-from-txt-with-pandas). – jpp Sep 28 '18 at 13:41
  • When I try to do that it gives me an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 4: unexpected end of data – Doughnut Sep 28 '18 at 13:45
  • 1
    @Doughnut, This has come up many time on SO. Did you do a search? – jpp Sep 28 '18 at 13:47