Create a list of pairs of values from two dataframe columns

Viewed 6389

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)...]
4 Answers

Try this:

list(zip(df['lat'],df['lon']))

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.

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 (:

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)]
Related