I am trying to write python program that reads a .csv file. I have in the input file 4 columns/fields and I want to only have 2 in the output with one being a new one.
This is the input I am using:
MID,REP,NAME,NEPTUN
0,,"people's front of judea",GM6MRT
17,,Steve Jobs,NC3J0K
,0,Brian,RQQCFE
19,9,Pontius Pilate,BQ6IAJ
1,,N. Jesus,QDMXVF
18,,Bill Gates,D1CXLO
0,,"knights who say NI",CZN5JA
,1,"Robin, the brave",BWQ5AU
17,19,"Gelehed, the pure",BY9B8G
then the output should be something like this(not full output):
NEPTUN,GROWTH
BQ6IAJ,-0.5263157894736842
BWQ5AU,inf
BY9B8G,0.11764705882352941
RQQCFE,0
The new field called GROWTH
is calculated by (REP-MID)/MID.
So, I am using two lists to do that:
import csv
L = []
s =[]
with open('input.csv', 'rb') as R:
reader = csv.DictReader(R)
for x in reader:
if x['MID'] != '' or '0' and x['REP'] == '':
Growth = -float(x['MID'])/float(x['MID'])
L.append(x)
s.append(Growth)
elif x['MID'] != '' or '0':
Growth = (float(x['REP']))-float(x['MID'])/float(x['MID'])
L.append(x)
s.append(Growth)
elif x['MID'] and x['REP'] == '' or '0' :
Growth = 0
L.append(x)
s.append(Growth)
else:
Growth = float("inf")
L.append(x)
s.append(Growth)
for i in range(len(s)):
L[i]['GROWTH'] = i
R.close()
with open('output.csv', 'wb') as output:
fields = ['NEPTUN', 'GROWTH']
writer = csv.DictWriter(output, fieldnames=fields, extrasaction='ignore')
writer.writeheader()
writer.writerows(L)
output.close()
Now, I am not even sure if the code is correct or does what I aim it for, because I am stuck at a ZeroDivisionError: float division by zero
at the first if
condition and I tried many ways to avoid it but I get the same error.
I thought the problem is that when there are no values for MID
field, I think the dictionary gives it ``
value and that can't be transformed to 0
by float()
. But it seems that is not the problem, but honestly I have no idea now, so that is why I am asking here.
the full error:
Growth = -float(x['MID'])/float(x['MID'])
ZeroDivisionError: float division by zero
Any hints about this are greatly valued.