rgraulus
rgraulus

Reputation: 41

How to convert the results of a for loop into pandas data frame?

Using the Haversine formula for distance calculation on a great circle, I use the following code to calculate the coordinates of any point between a known start location (with lat1/lon1) and a known destination (with lat2/lon2):

Here's the complete code:

from math import radians, sin, cos, acos, atan2, sqrt, pi

#enter the following numbers in the corresponding input fields:
#lat1 = starting latitude = 33.95 
#lon1 = starting longitude = -118.40
#lat2 = destination latitude = 40.6333 
#lon2= destination longitude = -73.7833
lat1 = radians(float(input("Starting latitude: ")))
lon1 = radians(float(input("Starting longitude: ")))
lat2 = radians(float(input("Destination latitude: ")))
lon2 = radians(float(input("Destination longitude: ")))

#Haversine formula to calculate the distance, in radians, between starting point and destination:
d = ((6371.01 * acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(lon1 - lon2)))/1.852)/(180*60/pi)  

import numpy as np
x = np.arange(0, 1, 0.2)
for f in x:
    A=sin((1-f)*d)/sin(d)
    B=sin(f*d)/sin(d)
    x = A*cos(lat1)*cos(lon1) +  B*cos(lat2)*cos(lon2)
    y = A*cos(lat1)*sin(lon1) +  B*cos(lat2)*sin(lon2)
    z = A*sin(lat1)           +  B*sin(lat2)
    lat_rad=atan2(z,sqrt(x**2+y**2))
    lon_rad=atan2(y,x)
    lat_deg = lat_rad*180/pi
    lon_deg = lon_rad*180/pi
    print('%.2f' %f, '%.4f' %lat_deg, '%.4f' %lon_deg)

I use the np.arange() function to do a fractional iteration, f, between 0 (the starting point) and 1 (the destination).

The output of the for loop is:

0.00 33.9500 -118.4000
0.20 36.6040 -110.2685
0.40 38.6695 -101.6259
0.60 40.0658 -92.5570
0.80 40.7311 -83.2103

Where, the first number is the fraction (f); the second number is the latitude (lat_deg) and the third number is the longitude (lon_deg).

My question is: how do I convert the output of my code into a pandas (3x6) data frame with the data arranged in 3 columns with header Fraction (col1), Latitude (col2), Longitude (col3)?

Once the output is in a pandas data frame I can then easily write the data into a CSV file.

Upvotes: 0

Views: 56

Answers (1)

Lars Skaug
Lars Skaug

Reputation: 1386

You're almost there. With the following modifications, you will be able to get your CSV:

  1. Append your values to a list instead of printing them.
  2. Convert the result to a dataframe

Below is your code with the required updates. I have now tested this and it works all the way to the final CSV.

import numpy as np
import pandas as pd
from math import radians, sin, cos, acos, atan2, sqrt, pi

# Numbers per your instructions
lat1 = radians(float(33.95))
lon1 = radians(float(-118.40))
lat2 = radians(float(40.6333))
lon2 = radians(float(-73.7833))

#Haversine formula to calculate the distance, in radians, between starting point and destination:
d = ((6371.01 * acos(sin(lat1)*sin(lat2) + cos(lat1)*cos(lat2)*cos(lon1 - lon2)))/1.852)/(180*60/pi)  

x = np.arange(0, 1, 0.2)

# An empty list into which we'll append each list of values
res = []

for f in x:
    A=sin((1-f)*d)/sin(d)
    B=sin(f*d)/sin(d)
    x = A*cos(lat1)*cos(lon1) +  B*cos(lat2)*cos(lon2)
    y = A*cos(lat1)*sin(lon1) +  B*cos(lat2)*sin(lon2)
    z = A*sin(lat1)           +  B*sin(lat2)
    lat_rad=atan2(z,sqrt(x**2+y**2))
    lon_rad=atan2(y,x)
    lat_deg = lat_rad*180/pi
    lon_deg = lon_rad*180/pi
    # Add the desired values, creating a list of lists
    res.append([f, lat_deg, lon_deg])

# Convert the result to a dataframe
res_df= pd.DataFrame(res, columns=['Fraction', 'Latitude', 'Longitude'])

# Voila! You can now save to CSV
res_df.to_csv('coordinates.csv', index=False)   


Upvotes: 1

Related Questions