0

I am trying to convert all of the zip codes in a 'zip_code" column into states using zipcode 2.0.0 package.

zip=f['zip_code']
zip=zip.astype(int)
zip=zip.astype(str)
for i in zip:
    myzip = zipcode.isequal(i)
    print(myzip.state)

I have converted the zip codes to string because myzip accepts strings only. However, when I try to print out the corresponding states, it gives an error:

AttributeError: 'NoneType' object has no attribute 'state'

What is the problem here? Package here

datalearner
  • 3
  • 1
  • 2
  • `zip` is a reserved keyword in python; please use something else. – Reblochon Masque Oct 03 '17 at 16:26
  • 7
    @ReblochonMasque, technically, `zip` is not a keyword, but a built-in function. Still a reserved name that OP should avoid using for his variables. – randomir Oct 03 '17 at 16:27
  • @brddawg I mean, possibly. We don't know what `f['zip_code']` is and `astype` might be a lift of `str` to operate on a collection of some zipcode-like object. – Adam Smith Oct 03 '17 at 16:32
  • @datalearner your input method and sample data would help. – brddawg Oct 03 '17 at 16:36
  • @Adam Smith just found a few issues with that https://stackoverflow.com/questions/22231592/pandas-change-data-type-of-series-to-string - either zip.astype(basestring) or zip.apply(str) should work shown in the answer. – brddawg Oct 03 '17 at 16:36
  • @brddawg why do you think `f` is a pandas array? – Adam Smith Oct 03 '17 at 16:37
  • @AdamSmith good point - results in searching for that method on so returned pandas & nymph with pandas being the most common. good tag to add. – brddawg Oct 03 '17 at 16:43
  • 1
    `zip` is not *reserved*, which would imply one *cannot* reuse it. It is simply predefined, meaning one *should* not reuse it without understanding the consequences. `class` is an example of a reserved keyword, which is why one uses something like `cls` as the conventional first argument to a class method. – chepner Oct 03 '17 at 16:54
  • What is `f`? Please see [ask] and provide a [mcve] in the future. – juanpa.arrivillaga Oct 03 '17 at 17:05

1 Answers1

2

According to here: http://pythonhosted.org/zipcode/, the isequal method can return a Zip object or None if the zipcodes are not equal. Therefore you should only print the state if you get back a valid zipcode. Try this:

zip=f['zip_code']
zip=zip.astype(int)
zip=zip.astype(str)
for i in zip:
    myzip = zipcode.isequal(i)
    if myzip:
        print(myzip.state)
Stuart Buckingham
  • 1,574
  • 16
  • 25