1

I have a field for geo-co-ordinates in my pandas dataframe. For some reason it is treating it as a string.

geoward.loc[1, 'coordinates']

output

'[[73.77359300000002,18.547145],[73.773696,18.546857],[73.77373,18.546758000000004],[73.77389,18.546786],[73.773971,18.546785999999997],[73.774031,18.546775999999998],[73.774092,18.546752],[73.7742,18.546692],[73.774329,18.546611],[73.77442,18.54656],[73.774505,18.546529],[73.774841,18.546381],[73.774863,18.546373000000003],[73.775058,18.546299],[73.775229,18.546243999999998],[73.775425,18.546182],[73.775694,18.546111]]'

Here I want it as a list, so that I can access each element from it. i.e coordinates[0] =[[73.77359300000002,18.547145] and further each float value from it.

How can I convert the string so that I can access it.

NSP
  • 963
  • 4
  • 13
  • 23
  • You have used enclosed your list with '. Please remove ' from the declaration. – Ravi Joshi Jun 19 '20 at 05:57
  • @RaviJoshi Sorry my question was ambiguous. I edited it now. The coordinates are stored in a dataframe , and the type is string. – NSP Jun 19 '20 at 06:03
  • use `ast.literal_eval()` – deadshot Jun 19 '20 at 06:03
  • Fix the dataframe on creation or read about `ast.literal_eval` to get the list from the string: [using-pythons-eval-vs-ast-literal-eval](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) – Patrick Artner Jun 19 '20 at 06:04

1 Answers1

-1

Only use eval function.

coordinates = '[[73.77359300000002,18.547145],[73.773696,18.546857],[73.77373,18.546758000000004],[73.77389,18.546786],[73.773971,18.546785999999997],[73.774031,18.546775999999998],[73.774092,18.546752],[73.7742,18.546692],[73.774329,18.546611],[73.77442,18.54656],[73.774505,18.546529],[73.774841,18.546381],[73.774863,18.546373000000003],[73.775058,18.546299],[73.775229,18.546243999999998],[73.775425,18.546182],[73.775694,18.546111]]'

coordinates = eval(coordinates)

print(coordinates[0])
print('lat', coordinates[0][0])
print('long', coordinates[0][1])