合并度分数据列,处理进位到下一个度数。(Python)
我遇到了一种奇怪的数据格式,正在为此烦恼。这是一个CSV文件,里面有一个时间戳列,还有一个表示纬度分钟的列(是个小数),以及一个表示经度分钟的列(也是小数)。数据中还包含一个起始的纬度和经度(以度为单位),但只有一个起始值。我需要把纬度和经度的分钟列与起始值结合起来,并转换成度和小数度的格式。我对这种格式感到困惑。
lat = 45
long = 75
data = {
'time': [
'2024-03-27 12:00:00', '2024-03-27 12:00:01', '2024- 03-27 12:00:02', '2024-03-27 12:00:03', '2024-03-27 12:00:04', '2024-03-27 12:00:05'
],
'lat_minutes': [
59.9955, 59.9963, 0.0180, 0.0230, 0.0050, 59.6500
],
'long_minutes': [
59.0250, 59.0750, 0.0020, 0.1850, 0.0750, 59.075
]
}
df = pd.DataFrame(data)
time lat_minutes long_minutes
0 2024-03-27 12:00:00 59.9955 59.025
1 2024-03-27 12:00:01 59.9963 59.075
2 2024-03-27 12:00:02 0.0180 0.002
3 2024-03-27 12:00:03 0.0230 0.185
4 2024-03-27 12:00:04 0.0050 0.075
5 2024-03-27 12:00:05 59.6500 59.075
我需要输出一个新列,格式是度.小数,计算方法是把分钟列的值加到起始的纬度和经度值上。当分钟超过60时,要加上一个完整的度;如果分钟在减少并且超过了0,变成59.9999时,则要减去一个度。
输出应该是这样的:
time lat_minutes long_minutes Latitude Longitude
0 2024-03-27 12:00:00 59.9955 59.025 45.999925 75.98375
1 2024-03-27 12:00:01 59.9963 59.075 45.9999383 75.984583
2 2024-03-27 12:00:02 0.0180 0.002 46.00030 76.0003
3 2024-03-27 12:00:03 0.0230 0.185 46.00383 76.00308
4 2024-03-27 12:00:04 0.0050 0.075 46.00125 76.00125
5 2024-03-27 12:00:05 59.6500 59.075 45.99416 75.98458
2 个回答
-1
我猜你是在寻找类似下面的内容:
def formDegrees(degree:float, offset: float) -> float:
# create a decinmal degree value from datum + offset
if int(degree) == degree and offset < 60.0:
# The simple case
return degree + offset/60
deg_frac = (degree -int(degree))*60
deg_frac += offset
return int(degree) + deg_frac/60
使用这个函数,给出以下内容:
start_lat = 45
lat_minutes = [59.9955, 59.9963, 60.0180, 60.0230, 60.0050, 59.6500]
执行:
for offset in lat_minutes]:
print (offset, formDegrees(start_lat, offset))
得到的结果是:
59.9955 45.999925
59.9963 45.99993833333333
60.018 46.0003
60.023 46.00038333333333
60.005 46.000083333333336
59.65 45.994166666666665
0
我相信这段代码可以简化得更短,但现在这样也能正常工作(经度的代码可以重复使用)。
# calculate how much the minutes changed since the preceding row
delta = df['lat_minutes'] - df['lat_minutes'].shift(1)
# initialise the new degrees column to all zeros
df['lat'] = 0
# if minutes decreases by more than 30
# treat it as having moved forward over a degree boundary
# => record a +1 degree offset at that row
df.loc[delta < -30, 'lat'] += 1
# if minutes increases by more than 30
# treat it as having moved backward over a degree boundary
# => record a -1 degree offset at that row
df.loc[delta > 30, 'lat'] -= 1
# final degrees = cumulative sum of above 'offsets', plus base offset, plus minutes/60
df['lat'] = df['lat'].cumsum() + lat + df['lat_minutes'] / 60
演示链接: https://www.online-python.com/rKvMuwq2sC
补充:也许可以稍微整理得更好一些……
delta = df['lat_minutes'] - df['lat_minutes'].shift(1)
offset = (
(delta < -30).astype(int)
-
(delta > 30).astype(int)
)
df['lat'] = offset.cumsum() + lat + df['lat_minutes'] / 60