Home > database >  How to append only the numbers in a row to a variable using float and an if statement in a for loop
How to append only the numbers in a row to a variable using float and an if statement in a for loop

Time:11-18

Given a data set with the goal of graphing the data these issues arise:

  • The header is an entry in the list,
  • Some of the entries are blank (data missing),
  • Even the numbers are in the form of strings
income=[]
fertility=[]
for row in csv:
  income.append(row[2])
  fertility.append(row[3])

print(income)
print(fertility)

I am trying to modify the above for loop that appends only the numerical values of the row using the float function coded below.

def isNumeric(s):
   try:
      s = float(s)
      return True
   except:
      return False

Below is my attempt, that is not appending the numerical values of the rows only giving me blank sets for income and fertility.

income=[]
fertility=[]
for row in csv:
  if isNumeric(row[2])=='True' and isNumeric(row[3])=='True':
    float(row[2])
    float(row[3])
    income.append(float(row[2]))
    fertility.append(float(row[3]))



print(income)
print(fertility)

CodePudding user response:

You can do this more simply by just doing both float conversions in a single try/except:

income = []
fertility = []
for row in csv:
    try:
        i, f = float(row[2]), float(row[3])
        income.append(i)
        fertility.append(f)
    except ValueError:
        pass

If either float() call raises ValueError, nothing will be appended, and the loop will just continue on to the next row.

CodePudding user response:

Samwise's response is a good one - it's simple and it is very pythonic - it tries to change the strings into floats and if that fails, it doesn't update the lists.

If you want your code to work, though, you can try it with these corrections:

income=[]
fertility=[]
for row in csv:
  if isNumeric(row[2]) and isNumeric(row[3]):
    income.append(float(row[2]))
    fertility.append(float(row[3]))

print(income)
print(fertility)
  • Related