0

i have multiple csv files (n) with fixed headers and 100 rows, and i'm trying to calculate the average (or other things such as Min or Max) of all [i][j] elements of these tables and store it in one final csv table. I tried genfromtxt but it did not workout. Here is my code:

import numpy as np
from numpy import genfromtxt


a=genfromtxt('C:\\Users\\my_pc\\Desktop\\a1.csv',delimiter=';' , skip_header=1, dtype=None, encoding='utf_8')
b=genfromtxt('C:\\Users\\my_pc\\Desktop\\a2.csv',delimiter=';' , skip_header=1, dtype=None, encoding='utf_8')
c=genfromtxt('C:\\Users\\my_pc\\Desktop\\a3.csv', delimiter=';' , skip_header=1, dtype=None, encoding='utf_8')

#average
d = (a + b+ c) /3
print(d)

which i get this error :

enter image description here

How can i do this ? and also please tell me, whether genfromtxt parameter is right or not?)

Saeid Hedayati
  • 83
  • 1
  • 3
  • 12
  • If you showed the content of your csv files as text (what they are) instead of through a spreadsheet image, we could try to reproduce... Remember, a csv file is a **text** file! – Serge Ballesta Mar 15 '19 at 13:55
  • @Serge Ballesta this spreadsheet something that i randomly generated in excel and saved it as csv. But it represent the exact format of my data – Saeid Hedayati Mar 15 '19 at 13:59
  • That is not the question. I can copy paste from a csv presented as text, but not from an image. It is much easier to help when the question contains a [mcve]... – Serge Ballesta Mar 15 '19 at 14:11
  • @Justice_Lords makes no difference as long as it wokrs better. but please remember that the final result should be in a data frame, so i can use it for further calculations. tnx – Saeid Hedayati Mar 15 '19 at 14:13

1 Answers1

1
import pandas as pd
df=pd.read_csv("a1.csv")
for i in range(2,21):
       filename="a"+str(i)+".csv"
       df+=pd.read_csv(filename)
df=df/20

This should do the trick..

Justice_Lords
  • 949
  • 5
  • 14
  • One more question, how should i put this in a for loop, because i have 20 data sets , could you help me with that as well? – Saeid Hedayati Mar 15 '19 at 14:45
  • @SaeidHedayati Can you try now? – Justice_Lords Mar 15 '19 at 14:55
  • sorry for the late respond. I tried it but i just keep getting this error `TypeError: unsupported operand type(s) for +: 'float' and 'str'` . – Saeid Hedayati Mar 18 '19 at 09:54
  • @SaeidHedayati You have to post full code so that I can help you. But I think it would be better if you post another question with sample datasets. Maybe try to load the data individually and check for its **type**. I think this problem has something to do type conversion. Try to convert "str" to "float" before adding. – Justice_Lords Mar 18 '19 at 10:12