如何将for循环的结果转换为熊猫数据帧?

时间:2020-08-06 21:35:42

标签: pandas export-to-csv

使用Haversine公式计算大圆上的距离,我使用以下代码来计算已知起始位置(使用lat1 / lon1)和已知目的地(使用lat2 / lon2)之间的任何点的坐标:< / p>

这是完整的代码:

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)

我使用np.arange()函数在0(起点)和1(目的地)之间进行小数迭代f。

for循环的输出为:

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

第一个数字是分数(f);第二个数字是纬度(lat_deg),第三个数字是经度(lon_deg)。

我的问题是:如何将代码输出转换为熊猫(3x6)数据帧,并将数据分为3列,标题为小数(col1),纬度(col2),经度(col3)?

一旦输出位于熊猫数据框中,我便可以轻松地将数据写入CSV文件。

1 个答案:

答案 0 :(得分:1)

您快到了。经过以下修改,您将可以获取CSV:

  1. 将您的值附加到列表中,而不是打印它们。
  2. Convert the result to a dataframe

下面是带有所需更新的代码。现在,我已经对此进行了测试,并且可以一直运行到最终的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)