如何在Python中将十进制度数转换为度分秒?是否已经有现成的公式可用?
如何在Python中将十进制度数转换为度分秒?是否已经有现成的公式可用?
# Program to convert degree to Degree, Minutes and Seconds
# Using try and except for int data validations
try:
# Requesting input degree from user
print ("degree to Degree Minutes seconds converter ". upper ())
degree = float(input ("\nEnter Degree: "))
# Casting input from float to int
degree_d = int(degree)
# Working on minutes
minute =60 * (degree - degree_d)
minutes = int(minute)
# Working on seconds
second = 60 * (minute - minutes)
# Rounding seconds to whole number
seconds= round(second)
# print
print (f"\nThe Answer In Degree-Minutes-Seconds are: \n{degree_d}°{minutes}'{seconds}\" ✓\n ")
#Except
except ValueError:
print ("Wrong Input ")
clean_lat_long()
。使用pip install dataprep
安装DataPrep。from dataprep.clean import clean_lat_long
df = pd.DataFrame({"coord": [(45.5003, -122.4420), (5.8833, -162.0833)]})
df2 = clean_lat_long(df, "coord", output_format="dms")
# print(df2)
coord coord_clean
0 (45.5003, -122.442) 45° 30′ 1.08″ N, 122° 26′ 31.2″ W
1 (5.8833, -162.0833) 5° 52′ 59.88″ N, 162° 4′ 59.88″ W
或者如果纬度和经度在不同的列中:
df = pd.DataFrame({"latitude": [45.5003, 5.8833], "longitude": [-122.4420, -162.0833]})
df2 = clean_lat_long(df, lat_col="latitude", long_col="longitude", output_format="dms")
# print(df2)
latitude longitude latitude_longitude
0 45.5003 -122.4420 45° 30′ 1.08″ N, 122° 26′ 31.2″ W
1 5.8833 -162.0833 5° 52′ 59.88″ N, 162° 4′ 59.88″ W
import sys
import math
dd = float(sys.argv[1])
f,d = math.modf(dd)
f,m = math.modf(60*f)
s = round(60*f, 6)
print(int(d), int(m), s)
def to_dms(decimal_degrees):
# convert degrees into dms and a sign indicator
degrees = np.array(decimal_degrees)
sign = np.where(degrees < 0, -1, 1)
r, s = np.divmod(np.round(np.abs(degrees) * 3600, 1), 60)
d, m = np.divmod(r, 60)
# np.transpose([d, m, s]*sign) # if you wanted signed results
return np.transpose([d, m, s, sign])
# print("array test:", to_dms([101.816652, -101.816653]))
# array test: [[101. 48. 59.9000000000232831 1.] [101. 49. 0. -1.]]
def dms_to_deg(dms):
import math
import numpy as np
a=math.fabs(dms)
d=a//10000
m=(a-d*10000)//100
s=(a-d*10000-m*100)
deg=(d+m/60+s/3600)*np.sign(dms)
return deg
#---Usage
r1=dms_to_deg(243055.25)
r2=dms_to_deg(-243055.25)
print(r1,r2)