4

This should be an easy one but I just can't work it out. I have a dataframe with a lon and lat column, I'd like to make a list where the lon and lat values are in pairs.

The dataframe looks like this:

    amenity                               name        lat        lon
0   school        George Bath Elementary School  40.722452 -75.386650
1   school        Dana L Lyon Elementary School  42.337774 -77.317131
2   school                  Bath Village School  44.168952 -71.963701
3   school                          Bath School  35.476832 -76.811605
4   school                          Hyde School  43.905080 -69.822825

I need a list like this:

[(40.722452, -75.386650), (42.337774, -77.317131), (44.168952, -71.963701)...]
Kim_Turtle
  • 63
  • 1
  • 8
  • 3
    Does this answer your question? [How to form tuple column from two columns in Pandas](https://stackoverflow.com/questions/16031056/how-to-form-tuple-column-from-two-columns-in-pandas) – talatccan Mar 04 '20 at 18:59
  • Thankyou yes, I just didn't know what I was looking for! – Kim_Turtle Mar 04 '20 at 20:09

4 Answers4

9

Try this:

list(zip(df['lat'],df['lon']))
carnava1
  • 319
  • 2
  • 6
1

Run:

df[['lat', 'lon']].apply(tuple, axis=1).tolist()

Steps:

  • df[['lat', 'lon']] - take 2 columns of interest,
  • apply(tuple, axis=1) - apply tuple function to each row (so far the result is a Series),
  • tolist() - convert this Series to an "ordinary" list.
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
1

You can do it this way:

 import pandas as  pd

 #Reading your data
 #data -> Pandas dataframe
 data = pd.read_excel('yourFile.xlsx')

 # Gets the column info
 lat = data['lat']
 lon = data['lon']

 #Process it
 result = []
 for i in range(len(lat)):
     #Adding to result based on indexes
     result.append((lat[i], lon[i]))

 print result

I tried to write it in an easily understandable way (:

Dautomne_
  • 94
  • 5
0

Try:

df.apply(lambda row: pd.Series([(row['lat'], row['lon'])]), axis=1)[0].tolist()

Result:

[(40.722452000000004, -75.38665),
 (42.337773999999996, -77.317131),
 (44.168952000000004, -71.963701),
 (35.476832, -76.811605),
 (43.90508, -69.822825)]
Pygirl
  • 12,969
  • 5
  • 30
  • 43