0

I have a list of tuples where each tuple contains a pair of coordinates. I would like to reverse the coordinates for each point.

I have a dataframe, and a specific column called "coord" contains a list of latitude and longitude coordinate pairs at each row, and I would like to reverse the pair of coordinates of each row.

As an example, the first row looks like this

 [(52.34725, 4.91790),
 (52.34715, 4.91797),
 (52.34742, 4.91723),
 (52.34752, 4.91713)]

I tried this function, but it does not work.

result =  [[p[1], p[0]] for p in x]

The expected output is:

[(4.91790, 52.34725),
 (4.91797, 52.34715),
 (4.91723, 52.34742),
 (4.91713, 52.34752)]
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Dragon
  • 1
  • 1
  • What does "*it does not work*" mean? Do you get errors or is it not what you expected? Your attempt should have worked in swapping the 2 items, but it creates a list of lists, instead of a list of tuples. You should have used `(p[1],p[0])`. – Gino Mempin Aug 14 '22 at 11:40
  • Does this answer your question? [Swap values in a tuple/list inside a list in python?](https://stackoverflow.com/questions/13384841/swap-values-in-a-tuple-list-inside-a-list-in-python) – Gino Mempin Aug 14 '22 at 11:40
  • i got the same input ,without reverse . i am no sure why but other method reversed down works fine for me .thanks for help – Dragon Aug 14 '22 at 11:42
  • It may be because it's in a dataframe, which isn't shown here. – Gino Mempin Aug 14 '22 at 11:47

3 Answers3

1

Try:

reversed = [item[::-1] for item in x]
Nuri Taş
  • 3,828
  • 2
  • 4
  • 22
  • thanks , this works for me . i tried it for first row and it works but how could i do it for each row in specific column ? – Dragon Aug 14 '22 at 11:29
  • It is hard to understand what you want to achieve from this comment. Could you update your question, or post another question including the dataframe and a more clear desired output? – Nuri Taş Aug 14 '22 at 11:34
  • it is fine ,it worked great nw .tahnks for help – Dragon Aug 14 '22 at 11:40
0
y = [(xx[1],xx[0]) for xx in x]
y  # [(4.9179, 52.34725), (4.91797, 52.34715), (4.91723, 52.34742), (4.91713, 52.34752)]
crissal
  • 2,547
  • 7
  • 25
0

Another possible solution:

y = []
for i, j in x:
  y.append((j, i))

Output:

[(4.9179, 52.34725), (4.91797, 52.34715), (4.91723, 52.34742), (4.91713, 52.34752)]
PaulS
  • 21,159
  • 2
  • 9
  • 26