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

gra草

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

这是完整的代码:

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)。

我的问题是:如何将我的代码输出转换为pandas(3x6)数据帧,数据以3列的形式排列,标题为小数(col1),纬度(col2),经度(col3)?

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

拉斯·斯考格

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

  1. 将值附加到列表中,而不是打印它们。
  2. 将结果转换为数据框

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


本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章