I'm working on a dataset for building permits. In the dataset there is a column that gives the location (lattitude and longitude) for the building permit. The data in the location column look like this:
0 (37.785719256680785, -122.40852313194863)
1 (37.78733980600732, -122.41063199757738)
2 (37.7946573324287, -122.42232562979227)
3 (37.79595867909168, -122.41557405519474)
4 (37.78315261897309, -122.40950883997789)
Name: location, dtype: object
As you can see, the data is stored as strings. I wanted to store the lattitude and longitude in two separate columns, so I wrote the following code to accomplish this:
df.location = df.location.str.replace('(','')
df.location = df.location.str.replace(')','')
for i in range(len(df)):
if df.location[i] == np.nan:
df['lattitude'] = np.nan
else:
df['lattitude'] = df.location[i][0:df['location'][i].index(',')]
for i in range(len(df)):
if df.location[i] == np.nan:
df['longitude'] = np.nan
else:
df['longitude'] = df.location[i][0:df['location'][i].index(',')]
There is some missing data in the column, 1700 entries to be exact. So in order to avoid a key error, I wrote the if-else statement to fill in the new columns with np.nan anytime the loop would iterate to a missing entry.
When I ran the code, I got the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-72-81826748e81c> in <module>()
7 df['lattitude'] = np.nan
8 else:
----> 9 df['lattitude'] = df.location[i][0:df['location'][i].index(',')]
10
11 for i in range(len(df)):
AttributeError: 'float' object has no attribute 'index'
Can anybody spot the error I'm making?