I have a DataFrame with a column with different coordinates, clustered together in other lists, like this:
name OBJECTID geometry
0 NaN 1 ['-80.304852,-3.489302,0.0','-80.303087,-3.490214,0.0',...]
1 NaN 2 ['-80.27494,-3.496571,0.0',...]
2 NaN 3 ['-80.267987,-3.500003,0.0',...]
I want to separate the values and remove the '0.0', but keep them inside the lists to add them to a certain key in a dictionary, that looks like this:
name OBJECTID geometry
0 NaN 1 [[-80.304852, -3.489302],[-80.303087, -3.490214],...]
1 NaN 2 [[-80.27494, -3.496571],...]
2 NaN 3 [[-80.267987, -3.500003],...]
This is my code that didn't work where I tried to separate them in a for loop:
import panda as pd
import numpy as np
r = pd.read_csv('data.csv')
rloc = np.asarray(r['geometry'])
r['latitude'] = np.zeros(r.shape[0],dtype= r['geometry'].dtype)
r['longitude'] = np.zeros(r.shape[0],dtype= r['geometry'].dtype)
# Separating the latitude and longitude values form each string.
for i in range(0, len(rloc)):
for j in range(0, len(rloc[i])):
coord = rloc[i][j].split(',')
r['longitude'] = coord[0]
r['latitude'] = coord[1]
r = r[['OBJECTID', 'latitude', 'longitude', 'name']]
Edit: The result wasn't good because it printed out only one value for each one.
OBJECTID latitude longitude name
0 1 -3.465566 -80.151633 NaN
1 2 -3.465566 -80.151633 NaN
2 3 -3.465566 -80.151633 NaN
Bonus question: How cand I add all of these longitude and latitude values inside a tuple to use with geopy? Like this:
r['location'] = (r['latitude], r['longitude'])
So, instead, the geometry column would look like this:
geometry
[(-80.304852, -3.489302),(-80.303087, -3.490214),...]
[(-80.27494, -3.496571),...]
[(-80.267987, -3.500003),...]
Edit:
The data looked like this at first(for each row):
<LineString><coordinates>-80.304852,-3.489302,0.0 -80.303087,-3.490214,0.0 ...</coordinates></LineString>
I modified it with regex, using this code:
geo = np.asarray(r['geometry']);
geo = [re.sub(re.compile('<.*?>'), '', string) for string in geo]
And then I placed it in an array:
rv = [geo[i].split() for i in range(0,len(geo))]
r['geometry'] = np.asarray(rv)
When I call r['geometry'], the output is:
0 [-80.304852,-3.489302,0.0, -80.303087,-3.49021...
1 [-80.27494,-3.496571,0.0, -80.271963,-3.49266,...
2 [-80.267987,-3.500003,0.0, -80.267845,-3.49789...
Name: geometry, dtype: object
And r['geometry'][0] is:
['-80.304852,-3.489302,0.0',
'-80.303087,-3.490214,0.0',
'-80.302131,-3.491878,0.0',
'-80.300763,-3.49213,0.0']