0

I'm trying to create a function that imports a csv file which holds records for population per year (as strings). It imports a file which has the year in the 3rd column and the population count in the 4th.

It should remove the decimal point '.' and display the resulting population.

16122.83
16223.248

should become

1612283
16223248

When I try to do this I get: in print_population_list year, population = row[2], float(row[3]) ValueError: could not convert string to float: POP. This is my code:

import csv
file = csv.reader(open(filename))

year, population = 0, 0

for row in file:
    year, population = row[2], float(row[3])
    print year,":", population,

To do this I figured it should first be converted to a float and be multiplied by the highest number of decimal places, after which all zero's at the end should be removed (since the data doesn't all have the same number of decimal places). But I'm stuck at the float conversion.

1
  • 1
    Roger that, I removed my comment. Commented Oct 17, 2014 at 17:46

2 Answers 2

2

Most direct route:

>>> s = '16122.83'
>>> int(s.replace('.', ''))
1612283

While performance is probably not a big concern in your use case, a replace strategy is about 30% faster than the split-join strategy, based on a simple benchmark.

Benchmark Report
================

Options
-------

   name | rank | runs |     mean |        sd | timesBaseline
--------|------|------|----------|-----------|--------------
replace |    1 | 1000 | 0.009488 | 0.0006711 |           1.0
   join |    2 | 1000 |  0.01258 | 0.0007729 | 1.32589602108

Each of the above 2000 runs were run in random, non-consecutive order by
`benchmark` v0.1.5 (http://jspi.es/benchmark) 

For this problem, int is what you seem to need. But for related problems, using float instead of int would keep you in the floating point realm. The round(value, places) function also might be handy.

Sign up to request clarification or add additional context in comments.

Comments

1

This should do the trick

def decToNum(s):
    return int(''.join(s.split('.')))

>>> s = '16122.83'
>>> decToNum(s)
1612283

1 Comment

this gives me: in decToNum return int(''.join(s.split('.'))) ValueError: invalid literal for int() with base 10: 'POP'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.