Trying to understand the find_lat(loc) logic

Screen Link:

My Code:

def find_lat(loc):
    coords = re.findall("\(.+\)", loc)
    lat = coords.split(",")[0].replace("(", "")
    return lat

What I expected to happen:
I expected it to work.

What actually happened:
It throws an error

AttributeError                            Traceback (most recent call last)
<ipython-input-1-4999a1653547> in <module>
----> 9 data['hs_directory']['lat']=data['hs_directory']['Location 1'].apply(lat)
     10 data['hs_directory']['lat'][0]

/dataquest/system/env/python3/lib/python3.8/site-packages/pandas/core/ in apply(self, func, convert_dtype, args, **kwds)
   3846             else:
   3847                 values = self.astype(object).values
-> 3848                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3850         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()

<ipython-input-1-4999a1653547> in lat(col)
      3 def lat (col):
      4     coords=re.findall("\(.+\)",col)
----> 5     lat=coords.split(",")[0].replace("(","")
      6     return lat

AttributeError: 'list' object has no attribute 'split'```

In the below solution why is [0] being used after coords list, because the list hasn’t been split into 2 coordinates, the split happens after the use of the split function

import re
def find_lat(loc):
    coords = re.findall("\(.+\)", loc)
    lat = coords*[0]*.split(",")[0].replace("(", "")
    return lat
1 Like

Here we are using re.findall which return type is list. (a list of strings). So to extract string item from list we are using coords[0].

Consider this given example

import re
loc = "1110 Boston Road\nBronx, NY 10456\n(40.8276026690005, -73.90447525699966)"

coords = re.findall("\(.+\)", loc)
['(40.8276026690005, -73.90447525699966)']         # Return list

# Now if you apply `split` on  list it will give error as `split` is a string function.
lat = coords.split(",")[0].replace("(", "")
AttributeError: 'list' object has no attribute 'split'

# So here by using `[0]` we are extracting string from list `coords`
lat = coords[0].split(",")[0].replace("(", "")

Thank you for the quick and detailed reply. I found it very helpful.

1 Like