tablegis 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tablegis/__init__.py +21 -0
- tablegis/core.py +311 -0
- tablegis/utils.py +105 -0
- tablegis-0.0.1.dist-info/METADATA +215 -0
- tablegis-0.0.1.dist-info/RECORD +8 -0
- tablegis-0.0.1.dist-info/WHEEL +5 -0
- tablegis-0.0.1.dist-info/licenses/LICENSE +21 -0
- tablegis-0.0.1.dist-info/top_level.txt +1 -0
tablegis/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import pkgutil
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
# 获取当前包的路径
|
|
6
|
+
pkg_path = Path(__file__).parent
|
|
7
|
+
|
|
8
|
+
# 自动发现并导出所有模块中的函数
|
|
9
|
+
__all__ = []
|
|
10
|
+
for _, module_name, _ in pkgutil.iter_modules([str(pkg_path)]):
|
|
11
|
+
# 导入模块
|
|
12
|
+
module = __import__(f"{__name__}.{module_name}", fromlist=["*"])
|
|
13
|
+
# 遍历模块中的成员
|
|
14
|
+
for name, obj in inspect.getmembers(module):
|
|
15
|
+
# 只导出函数,并且不是私有函数(不以下划线开头)
|
|
16
|
+
if inspect.isfunction(obj) and not name.startswith('_'):
|
|
17
|
+
# 将函数添加到当前命名空间
|
|
18
|
+
globals()[name] = obj
|
|
19
|
+
# 将函数名添加到 __all__
|
|
20
|
+
if name not in __all__:
|
|
21
|
+
__all__.append(name)
|
tablegis/core.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# coding: utf-8
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import numpy as np
|
|
5
|
+
from scipy.spatial import cKDTree
|
|
6
|
+
import pyproj
|
|
7
|
+
from .utils import *
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def min_distance_onetable(df, lon='lon', lat='lat', idname='id', n=1, include_self=False) -> pd.DataFrame:
|
|
12
|
+
"""
|
|
13
|
+
计算DataFrame中每个点的最近n个点(可选择是否包含自身)
|
|
14
|
+
|
|
15
|
+
参数:
|
|
16
|
+
df (DataFrame): 输入数据
|
|
17
|
+
lon (str): 经度列名
|
|
18
|
+
lat (str): 纬度列名
|
|
19
|
+
id (str): ID列名,默认为'id'
|
|
20
|
+
n (int): 要查找的最近邻数量
|
|
21
|
+
include_self (bool): 是否包含自身点,默认为False
|
|
22
|
+
|
|
23
|
+
返回:
|
|
24
|
+
DataFrame: 添加了最近邻信息的副本
|
|
25
|
+
示例:
|
|
26
|
+
import pandas as pd
|
|
27
|
+
import tablegis as tg
|
|
28
|
+
|
|
29
|
+
# 创建两个示例DataFrame
|
|
30
|
+
df2 = pd.DataFrame({
|
|
31
|
+
'id': ['A', 'B', 'C', 'D'],
|
|
32
|
+
'lon2': [116.403, 116.407, 116.404, 116.408],
|
|
33
|
+
'lat2': [39.914, 39.918, 39.916, 39.919]
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
# 计算最近的1个点
|
|
37
|
+
result = tg.min_distance_onetable(df2,'lon2','lat2',idname='id',n=1)
|
|
38
|
+
print("结果示例(距离单位:米):")
|
|
39
|
+
print(result)
|
|
40
|
+
print(result2)
|
|
41
|
+
结果展示:
|
|
42
|
+
**最近1个点**
|
|
43
|
+
id lon2 lat2 nearest1_id nearest1_lon2 nearest1_lat2 nearest1_distance
|
|
44
|
+
0 p1 114.01 30.01 p2 114.05 30.05 5881.336911
|
|
45
|
+
1 p2 114.05 30.05 p1 114.01 30.01 5881.336911
|
|
46
|
+
2 p3 114.12 30.12 p2 114.05 30.05 10289.545038
|
|
47
|
+
|
|
48
|
+
"""
|
|
49
|
+
# 参数验证
|
|
50
|
+
if n < 1:
|
|
51
|
+
raise ValueError("n must be > 0")
|
|
52
|
+
if lon not in df.columns or lat not in df.columns:
|
|
53
|
+
raise ValueError("Longitude or latitude column not found")
|
|
54
|
+
if idname not in df.columns:
|
|
55
|
+
raise ValueError("ID column not found")
|
|
56
|
+
if df.empty:
|
|
57
|
+
return df # 返回空 DataFrame 而不是抛出异常
|
|
58
|
+
detected_crs = detect_crs(df, lon, lat)
|
|
59
|
+
# 创建结果副本
|
|
60
|
+
result = df.copy()
|
|
61
|
+
|
|
62
|
+
# 处理空数据或数据量不足的情况
|
|
63
|
+
if len(df) == 0 or (len(df) == 1 and not include_self):
|
|
64
|
+
for i in range(1, n+1):
|
|
65
|
+
result[f'nearest{i}_{idname}'] = np.nan
|
|
66
|
+
result[f'nearest{i}_{lon}'] = np.nan
|
|
67
|
+
result[f'nearest{i}_{lat}'] = np.nan
|
|
68
|
+
result[f'nearest{i}_distance'] = np.nan
|
|
69
|
+
if n > 1:
|
|
70
|
+
result['mean_distance'] = np.nan
|
|
71
|
+
return result
|
|
72
|
+
|
|
73
|
+
# 提取坐标点
|
|
74
|
+
points, proj_crs = create_projected_kdtree(result, lon, lat)
|
|
75
|
+
|
|
76
|
+
# 创建KDTree
|
|
77
|
+
tree = cKDTree(points)
|
|
78
|
+
|
|
79
|
+
# 计算要查询的邻居数量
|
|
80
|
+
# 如果不包含自身,需要额外查询1个点(因为第一个是自身)
|
|
81
|
+
k_query = n + (0 if include_self else 1)
|
|
82
|
+
# 确保不超过数据集大小
|
|
83
|
+
k_query = min(k_query, len(df))
|
|
84
|
+
|
|
85
|
+
# 查询最近的k个点
|
|
86
|
+
distances, indices = tree.query(points, k=k_query, workers=-1)
|
|
87
|
+
|
|
88
|
+
# 处理单个邻居的情况(确保是二维数组)
|
|
89
|
+
if k_query == 1:
|
|
90
|
+
distances = distances.reshape(-1, 1)
|
|
91
|
+
indices = indices.reshape(-1, 1)
|
|
92
|
+
|
|
93
|
+
# 如果不包含自身,跳过第一列(自身点)
|
|
94
|
+
if not include_self and k_query > 1:
|
|
95
|
+
distances = distances[:, 1:]
|
|
96
|
+
indices = indices[:, 1:]
|
|
97
|
+
|
|
98
|
+
# 确保结果有正确的列数
|
|
99
|
+
current_k = distances.shape[1] if len(distances.shape) > 1 else 1
|
|
100
|
+
|
|
101
|
+
# 初始化结果数组
|
|
102
|
+
result_indices = np.full((len(df), n), -1, dtype=int)
|
|
103
|
+
result_distances = np.full((len(df), n), np.nan)
|
|
104
|
+
|
|
105
|
+
# 填充有效数据
|
|
106
|
+
valid_cols = min(current_k, n)
|
|
107
|
+
if valid_cols > 0:
|
|
108
|
+
if len(distances.shape) == 1:
|
|
109
|
+
result_indices[:, 0] = indices
|
|
110
|
+
result_distances[:, 0] = distances
|
|
111
|
+
else:
|
|
112
|
+
result_indices[:, :valid_cols] = indices[:, :valid_cols]
|
|
113
|
+
result_distances[:, :valid_cols] = distances[:, :valid_cols]
|
|
114
|
+
|
|
115
|
+
# 添加最近邻信息到结果DataFrame
|
|
116
|
+
for i in range(n):
|
|
117
|
+
# 获取当前列的索引
|
|
118
|
+
col_indices = result_indices[:, i]
|
|
119
|
+
|
|
120
|
+
# 初始化列
|
|
121
|
+
id_values = []
|
|
122
|
+
lon_values = []
|
|
123
|
+
lat_values = []
|
|
124
|
+
|
|
125
|
+
# 填充数据
|
|
126
|
+
for idx in col_indices:
|
|
127
|
+
if idx >= 0:
|
|
128
|
+
id_values.append(df.iloc[idx][idname])
|
|
129
|
+
lon_values.append(df.iloc[idx][lon])
|
|
130
|
+
lat_values.append(df.iloc[idx][lat])
|
|
131
|
+
else:
|
|
132
|
+
id_values.append(np.nan)
|
|
133
|
+
lon_values.append(np.nan)
|
|
134
|
+
lat_values.append(np.nan)
|
|
135
|
+
|
|
136
|
+
result[f'nearest{i+1}_{idname}'] = id_values
|
|
137
|
+
result[f'nearest{i+1}_{lon}'] = lon_values
|
|
138
|
+
result[f'nearest{i+1}_{lat}'] = lat_values
|
|
139
|
+
result[f'nearest{i+1}_distance'] = result_distances[:, i]
|
|
140
|
+
|
|
141
|
+
# 添加平均距离(当n>1时)
|
|
142
|
+
if n > 1:
|
|
143
|
+
dist_cols = [f'nearest{j+1}_distance' for j in range(n)]
|
|
144
|
+
result['mean_distance'] = result[dist_cols].mean(axis=1)
|
|
145
|
+
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def min_distance_twotable(df1, df2, lon1='lon1', lat1='lat1', lon2='lon2', lat2='lat2', df2_id='id', n=1,
|
|
150
|
+
crs1: Optional[str]=None, crs2: Optional[str]=None) -> pd.DataFrame:
|
|
151
|
+
"""
|
|
152
|
+
计算df1中每个点到df2中最近的n个点的距离
|
|
153
|
+
|
|
154
|
+
该函数使用KDTree算法高效计算两个DataFrame之间的最近邻距离。
|
|
155
|
+
坐标系统必须一致(当前仅支持WGS84/EPSG:4326)。
|
|
156
|
+
距离通过UTM投影计算,单位为米。
|
|
157
|
+
|
|
158
|
+
Parameters
|
|
159
|
+
----------
|
|
160
|
+
df1 : pd.DataFrame
|
|
161
|
+
源数据表,包含待查询的坐标点
|
|
162
|
+
df2 : pd.DataFrame
|
|
163
|
+
目标数据表,包含参考坐标点
|
|
164
|
+
lon1 : str, default='lon1'
|
|
165
|
+
df1的经度列名
|
|
166
|
+
lat1 : str, default='lat1'
|
|
167
|
+
df1的纬度列名
|
|
168
|
+
lon2 : str, default='lon2'
|
|
169
|
+
df2的经度列名
|
|
170
|
+
lat2 : str, default='lat2'
|
|
171
|
+
df2的纬度列名
|
|
172
|
+
df2_id : str, default='id'
|
|
173
|
+
df2中用于标识点的ID列名
|
|
174
|
+
n : int, default=1
|
|
175
|
+
要查找的最近邻数量
|
|
176
|
+
crs1 : str, optional
|
|
177
|
+
df1的坐标系统,如 'EPSG:4326'。如果为None则自动检测
|
|
178
|
+
crs2 : str, optional
|
|
179
|
+
df2的坐标系统,如 'EPSG:4326'。如果为None则自动检测
|
|
180
|
+
|
|
181
|
+
Returns
|
|
182
|
+
-------
|
|
183
|
+
pd.DataFrame
|
|
184
|
+
返回df1的副本,添加以下列:
|
|
185
|
+
- nearest{i}_{df2_id} : 第i近的点的ID
|
|
186
|
+
- nearest{i}_{lon2} : 第i近的点的经度
|
|
187
|
+
- nearest{i}_{lat2} : 第i近的点的纬度
|
|
188
|
+
- nearest{i}_distance : 距离(米)
|
|
189
|
+
- mean_distance : 前n个最近点的平均距离(当n>1时)
|
|
190
|
+
|
|
191
|
+
Raises
|
|
192
|
+
------
|
|
193
|
+
ValueError
|
|
194
|
+
- 如果n < 1
|
|
195
|
+
- 如果两个DataFrame的坐标系不一致
|
|
196
|
+
- 如果坐标范围不符合WGS84标准
|
|
197
|
+
|
|
198
|
+
Examples
|
|
199
|
+
--------
|
|
200
|
+
import pandas as pd
|
|
201
|
+
df1 = pd.DataFrame({
|
|
202
|
+
'id': [1, 2, 3],
|
|
203
|
+
'lon1': [116.404, 116.405, 116.406],
|
|
204
|
+
'lat1': [39.915, 39.916, 39.917]
|
|
205
|
+
})
|
|
206
|
+
df2 = pd.DataFrame({
|
|
207
|
+
'id': ['A', 'B', 'C'],
|
|
208
|
+
'lon2': [116.403, 116.407, 116.404],
|
|
209
|
+
'lat2': [39.914, 39.918, 39.916]
|
|
210
|
+
})
|
|
211
|
+
# 计算df1中每个点到df2中最近的那个点
|
|
212
|
+
result = tg.min_distance_twotable(df1, df2,lon1='lon1', lat1='lat1', lon2='lon2', lat2='lat2', df2_id='id', n=1)
|
|
213
|
+
print(result)
|
|
214
|
+
|
|
215
|
+
Notes
|
|
216
|
+
-----
|
|
217
|
+
- 距离计算使用UTM投影,确保精度
|
|
218
|
+
- 使用cKDTree进行高效的最近邻搜索
|
|
219
|
+
- 当n大于df2的点数时,缺失的邻居会用NaN填充
|
|
220
|
+
- 坐标系统必须为WGS84 (EPSG:4326)
|
|
221
|
+
"""
|
|
222
|
+
# 验证输入
|
|
223
|
+
if n < 1:
|
|
224
|
+
raise ValueError("参数 n 必须大于等于 1")
|
|
225
|
+
# 处理空数据情况
|
|
226
|
+
if len(df2) == 0 or len(df1) == 0:
|
|
227
|
+
for i in range(1, n + 1):
|
|
228
|
+
df1[f'nearest{i}_{df2_id}'] = np.nan
|
|
229
|
+
df1[f'nearest{i}_{lon2}'] = np.nan
|
|
230
|
+
df1[f'nearest{i}_{lat2}'] = np.nan
|
|
231
|
+
df1[f'nearest{i}_distance'] = np.nan
|
|
232
|
+
if n > 1:
|
|
233
|
+
df1['mean_distance'] = np.nan
|
|
234
|
+
return df1
|
|
235
|
+
# 检测或验证坐标系
|
|
236
|
+
detected_crs1 = detect_crs(df1, lon1, lat1)
|
|
237
|
+
detected_crs2 = detect_crs(df2, lon2, lat2)
|
|
238
|
+
|
|
239
|
+
# 如果用户指定了CRS,验证是否匹配
|
|
240
|
+
if crs1 is not None and crs1 != detected_crs1:
|
|
241
|
+
raise ValueError(
|
|
242
|
+
f"指定的 crs1={crs1} 与检测到的坐标系 {detected_crs1} 不匹配"
|
|
243
|
+
)
|
|
244
|
+
if crs2 is not None and crs2 != detected_crs2:
|
|
245
|
+
raise ValueError(
|
|
246
|
+
f"指定的 crs2={crs2} 与检测到的坐标系 {detected_crs2} 不匹配"
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
# 检查两个DataFrame的坐标系是否一致
|
|
250
|
+
if detected_crs1 != detected_crs2:
|
|
251
|
+
raise ValueError(
|
|
252
|
+
f"两个DataFrame的坐标系不一致!\n"
|
|
253
|
+
f"df1 坐标系: {detected_crs1}\n"
|
|
254
|
+
f"df2 坐标系: {detected_crs2}\n"
|
|
255
|
+
f"请确保两个数据集使用相同的坐标系统。"
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
# 创建结果副本
|
|
259
|
+
result = df1.copy()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# 将df1坐标投影到UTM(单位:米)
|
|
263
|
+
A_points, proj_crs = create_projected_kdtree(df1, lon1, lat1)
|
|
264
|
+
|
|
265
|
+
# 为df2创建转换器(使用相同的UTM投影)
|
|
266
|
+
transformer_b = pyproj.Transformer.from_crs(
|
|
267
|
+
"EPSG:4326",
|
|
268
|
+
proj_crs,
|
|
269
|
+
always_xy=True
|
|
270
|
+
)
|
|
271
|
+
lons_b = df2[lon2].values
|
|
272
|
+
lats_b = df2[lat2].values
|
|
273
|
+
x_b, y_b = transformer_b.transform(lons_b, lats_b)
|
|
274
|
+
B_points = np.column_stack((x_b, y_b))
|
|
275
|
+
|
|
276
|
+
# 创建KDTree进行高效搜索
|
|
277
|
+
tree = cKDTree(B_points)
|
|
278
|
+
|
|
279
|
+
# 查询最近的n个点
|
|
280
|
+
k = min(n, len(df2))
|
|
281
|
+
distances, indices = tree.query(A_points, k=k, workers=-1)
|
|
282
|
+
|
|
283
|
+
# 处理k=1时的维度问题
|
|
284
|
+
if k == 1:
|
|
285
|
+
distances = distances.reshape(-1, 1)
|
|
286
|
+
indices = indices.reshape(-1, 1)
|
|
287
|
+
|
|
288
|
+
# 添加最近邻信息
|
|
289
|
+
for i in range(k):
|
|
290
|
+
nearest_points = df2.iloc[indices[:, i]]
|
|
291
|
+
result[f'nearest{i+1}_{df2_id}'] = nearest_points[df2_id].values
|
|
292
|
+
result[f'nearest{i+1}_{lon2}'] = nearest_points[lon2].values
|
|
293
|
+
result[f'nearest{i+1}_{lat2}'] = nearest_points[lat2].values
|
|
294
|
+
result[f'nearest{i+1}_distance'] = distances[:, i] # 单位:米
|
|
295
|
+
|
|
296
|
+
# 添加缺失的列(当n > k时)
|
|
297
|
+
for i in range(k, n):
|
|
298
|
+
result[f'nearest{i+1}_{df2_id}'] = np.nan
|
|
299
|
+
result[f'nearest{i+1}_{lon2}'] = np.nan
|
|
300
|
+
result[f'nearest{i+1}_{lat2}'] = np.nan
|
|
301
|
+
result[f'nearest{i+1}_distance'] = np.nan
|
|
302
|
+
|
|
303
|
+
# 添加平均距离(当n > 1时)
|
|
304
|
+
if n > 1:
|
|
305
|
+
dist_cols = [f'nearest{i+1}_distance' for i in range(min(n, k))]
|
|
306
|
+
if dist_cols:
|
|
307
|
+
result['mean_distance'] = result[dist_cols].mean(axis=1)
|
|
308
|
+
else:
|
|
309
|
+
result['mean_distance'] = np.nan
|
|
310
|
+
|
|
311
|
+
return result
|
tablegis/utils.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""
|
|
2
|
+
辅助函数用于地理空间数据处理
|
|
3
|
+
|
|
4
|
+
Author: Non-existent987
|
|
5
|
+
License: MIT
|
|
6
|
+
"""
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pyproj
|
|
9
|
+
from typing import Tuple
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def detect_crs(df, lon_col: str, lat_col: str) -> str:
|
|
13
|
+
"""
|
|
14
|
+
检测DataFrame的坐标参考系统(CRS)
|
|
15
|
+
|
|
16
|
+
通过坐标范围自动检测是否为 WGS84 (EPSG:4326) 坐标系
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
df : pd.DataFrame
|
|
21
|
+
包含坐标数据的DataFrame
|
|
22
|
+
lon_col : str
|
|
23
|
+
经度列名
|
|
24
|
+
lat_col : str
|
|
25
|
+
纬度列名
|
|
26
|
+
|
|
27
|
+
Returns
|
|
28
|
+
-------
|
|
29
|
+
str
|
|
30
|
+
检测到的CRS,当前仅支持 'EPSG:4326'
|
|
31
|
+
|
|
32
|
+
Raises
|
|
33
|
+
------
|
|
34
|
+
ValueError
|
|
35
|
+
如果坐标范围不符合WGS84标准
|
|
36
|
+
"""
|
|
37
|
+
lons = df[lon_col].values
|
|
38
|
+
lats = df[lat_col].values
|
|
39
|
+
|
|
40
|
+
# 检查是否为WGS84范围
|
|
41
|
+
lon_in_range = (-180 <= lons.min() <= 180) and (-180 <= lons.max() <= 180)
|
|
42
|
+
lat_in_range = (-90 <= lats.min() <= 90) and (-90 <= lats.max() <= 90)
|
|
43
|
+
|
|
44
|
+
if lon_in_range and lat_in_range:
|
|
45
|
+
return 'EPSG:4326'
|
|
46
|
+
else:
|
|
47
|
+
raise ValueError(
|
|
48
|
+
f"坐标范围不符合WGS84 (EPSG:4326) 标准。\n"
|
|
49
|
+
f"经度范围: [{lons.min():.4f}, {lons.max():.4f}] (应在 [-180, 180])\n"
|
|
50
|
+
f"纬度范围: [{lats.min():.4f}, {lats.max():.4f}] (应在 [-90, 90])\n"
|
|
51
|
+
f"请检查您的坐标系统或坐标列是否正确,支持经纬度数据。"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def create_projected_kdtree(df, lon_col: str = 'lon', lat_col: str = 'lat') -> Tuple[np.ndarray, str]:
|
|
56
|
+
"""
|
|
57
|
+
将WGS84经纬度坐标转换为UTM投影坐标
|
|
58
|
+
|
|
59
|
+
根据数据中心点自动选择合适的UTM投影带,将地理坐标转换为平面坐标(米)
|
|
60
|
+
|
|
61
|
+
Parameters
|
|
62
|
+
----------
|
|
63
|
+
df : pd.DataFrame
|
|
64
|
+
包含WGS84坐标的DataFrame
|
|
65
|
+
lon_col : str, default='lon'
|
|
66
|
+
经度列名
|
|
67
|
+
lat_col : str, default='lat'
|
|
68
|
+
纬度列名
|
|
69
|
+
|
|
70
|
+
Returns
|
|
71
|
+
-------
|
|
72
|
+
points : np.ndarray
|
|
73
|
+
转换后的UTM坐标数组,形状为 (n, 2),单位为米
|
|
74
|
+
epsg_code : str
|
|
75
|
+
使用的UTM投影EPSG代码,格式如 'EPSG:32650'
|
|
76
|
+
|
|
77
|
+
Notes
|
|
78
|
+
-----
|
|
79
|
+
- UTM投影会根据数据中心点自动选择投影带
|
|
80
|
+
- 北半球使用 EPSG:326xx,南半球使用 EPSG:327xx
|
|
81
|
+
- 投影后的坐标单位为米,适合进行距离计算
|
|
82
|
+
"""
|
|
83
|
+
lons = df[lon_col].values
|
|
84
|
+
lats = df[lat_col].values
|
|
85
|
+
|
|
86
|
+
# 确定中心点(用于选择UTM区域)
|
|
87
|
+
center_lon, center_lat = np.mean(lons), np.mean(lats)
|
|
88
|
+
utm_zone = int((center_lon + 180) / 6) + 1
|
|
89
|
+
hemisphere = 'north' if center_lat >= 0 else 'south'
|
|
90
|
+
|
|
91
|
+
# EPSG code for WGS 84 / UTM zone
|
|
92
|
+
epsg_code = 32600 + utm_zone if hemisphere == 'north' else 32700 + utm_zone
|
|
93
|
+
|
|
94
|
+
# 创建转换器(从WGS84到UTM)
|
|
95
|
+
transformer = pyproj.Transformer.from_crs(
|
|
96
|
+
"EPSG:4326",
|
|
97
|
+
f"EPSG:{epsg_code}",
|
|
98
|
+
always_xy=True
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# 转换为UTM坐标
|
|
102
|
+
x, y = transformer.transform(lons, lats)
|
|
103
|
+
points = np.column_stack((x, y))
|
|
104
|
+
|
|
105
|
+
return points, f"EPSG:{epsg_code}"
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tablegis
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: A powerful Python library for geospatial data processing, analysis and conversion - integrating pandas with GIS operations
|
|
5
|
+
Author-email: Non-existent987 <jiaqi0425_000@163.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 Non-existent987
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/Non-existent987/tablegis
|
|
29
|
+
Project-URL: Bug Tracker, https://github.com/Non-existent987/tablegis/issues
|
|
30
|
+
Project-URL: Repository, https://github.com/Non-existent987/tablegis.git
|
|
31
|
+
Keywords: gis,geospatial,pandas,geopandas,shapefile,kml,geojson,spatial-analysis,geographic,geometry,mapping
|
|
32
|
+
Classifier: Programming Language :: Python :: 3
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Operating System :: OS Independent
|
|
35
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
36
|
+
Requires-Python: >=3.7
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
License-File: LICENSE
|
|
39
|
+
Requires-Dist: geopandas
|
|
40
|
+
Requires-Dist: pandas
|
|
41
|
+
Requires-Dist: numpy
|
|
42
|
+
Requires-Dist: shapely
|
|
43
|
+
Requires-Dist: simplekml
|
|
44
|
+
Requires-Dist: pyshp
|
|
45
|
+
Requires-Dist: geographiclib
|
|
46
|
+
Requires-Dist: kml2geojson
|
|
47
|
+
Requires-Dist: scipy
|
|
48
|
+
Requires-Dist: pyproj
|
|
49
|
+
Dynamic: license-file
|
|
50
|
+
|
|
51
|
+
# tablegis
|
|
52
|
+
|
|
53
|
+
`tablegis` is a Python package for geospatial data processing and analysis, built on `geopandas`, `pandas`, `shapely`, and `pyproj`. It provides a series of utility functions to simplify common GIS operations.
|
|
54
|
+
|
|
55
|
+
## Features
|
|
56
|
+
|
|
57
|
+
* **Distance Calculation**: Efficiently compute the nearest distance between DataFrames.
|
|
58
|
+
* **Spatial Analysis**: Create buffers (input in meters), Voronoi polygons, Delaunay triangulations, etc.
|
|
59
|
+
* **Format Conversion**: Easily convert between `GeoDataFrame` and formats like `Shapefile`, `KML`, etc.
|
|
60
|
+
* **Coordinate Aggregation**: Provides tools for aggregating coordinate points into grids.
|
|
61
|
+
* **Geometric Operations**: Includes merging polygons, calculating centroids, adding sectors, etc.
|
|
62
|
+
|
|
63
|
+
## Installation
|
|
64
|
+
|
|
65
|
+
1、You can install `tablegis` from PyPI:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install tablegis
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
2、Or, install the latest version directly from the GitHub repository:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pip install git+https://github.com/Non-existent987/tablegis.git
|
|
75
|
+
```
|
|
76
|
+
3、After downloading the project, it is convenient to import from local files for modification.
|
|
77
|
+
```bash
|
|
78
|
+
import sys
|
|
79
|
+
import pandas as pd
|
|
80
|
+
# Find the file path of the tablegis you downloaded.
|
|
81
|
+
sys.path.insert(0, r'C:\Users\Administrator\Desktop\tablegis')
|
|
82
|
+
# Now it can be imported.
|
|
83
|
+
import tablegis as tg
|
|
84
|
+
```
|
|
85
|
+
## Quick Start
|
|
86
|
+
|
|
87
|
+
Here is a simple example of how to use `tablegis`:
|
|
88
|
+
|
|
89
|
+
### 1. Find the nearest point (in df2) for each point in df1 and add its ID, longitude, latitude, and distance.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import pandas as pd
|
|
93
|
+
import tablegis as tg
|
|
94
|
+
|
|
95
|
+
# Create two example DataFrames
|
|
96
|
+
df1 = pd.DataFrame({
|
|
97
|
+
'id': [1, 2, 3],
|
|
98
|
+
'lon1': [116.404, 116.405, 116.406],
|
|
99
|
+
'lat1': [39.915, 39.916, 39.917]
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
df2 = pd.DataFrame({
|
|
103
|
+
'id': ['A', 'B', 'C', 'D'],
|
|
104
|
+
'lon2': [116.403, 116.407, 116.404, 116.408],
|
|
105
|
+
'lat2': [39.914, 39.918, 39.916, 39.919]
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
# Calculate the nearest 1 point
|
|
109
|
+
result = tg.min_distance_twotable(df1, df2, lon1='lon1', lat1='lat1', lon2='lon2', lat2='lat2', df2_id='id', n=1)
|
|
110
|
+
# Calculate the nearest 2 points
|
|
111
|
+
result2 = tg.min_distance_twotable(df1, df2, lon1='lon1', lat1='lat1', lon2='lon2', lat2='lat2', df2_id='id', n=2)
|
|
112
|
+
|
|
113
|
+
print("\nExample result (distance in meters):")
|
|
114
|
+
print(result)
|
|
115
|
+
print(result2)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
**Result Display:**
|
|
119
|
+
|
|
120
|
+
<table>
|
|
121
|
+
<tr>
|
|
122
|
+
<td style="vertical-align: top; padding-right: 50px;">
|
|
123
|
+
|
|
124
|
+
**Table df1:**
|
|
125
|
+
|
|
126
|
+
| id | lon1 | lat1 |
|
|
127
|
+
|----|-------|------|
|
|
128
|
+
| A | 114.0 | 30.0 |
|
|
129
|
+
| B | 114.1 | 30.1 |
|
|
130
|
+
|
|
131
|
+
</td>
|
|
132
|
+
<td style="vertical-align: top;">
|
|
133
|
+
|
|
134
|
+
**Table df2:**
|
|
135
|
+
|
|
136
|
+
| id | lon2 | lat2 |
|
|
137
|
+
|----|--------|-------|
|
|
138
|
+
| p1 | 114.01 | 30.01 |
|
|
139
|
+
| p2 | 114.05 | 30.05 |
|
|
140
|
+
| p3 | 114.12 | 30.12 |
|
|
141
|
+
|
|
142
|
+
</td>
|
|
143
|
+
</tr>
|
|
144
|
+
</table>
|
|
145
|
+
|
|
146
|
+
**Nearest 1 point:**
|
|
147
|
+
|
|
148
|
+
| id | lon1 | lat1 | nearest1_id | nearest1_lon2 | nearest1_lat2 | nearest1_distance |
|
|
149
|
+
|----|-------|------|-------------|---------------|---------------|-------------------|
|
|
150
|
+
| A | 114.0 | 30.0 | p1 | 114.01 | 30.01 | 1470.515926 |
|
|
151
|
+
| B | 114.1 | 30.1 | p3 | 114.12 | 30.12 | 2939.507557 |
|
|
152
|
+
|
|
153
|
+
**Nearest 2 points:**
|
|
154
|
+
|
|
155
|
+
| id | lon1 | lat1 | nearest1_id | nearest1_lon2 | nearest1_lat2 | nearest1_distance | nearest2_id | nearest2_lon2 | nearest2_lat2 | nearest2_distance | mean_distance |
|
|
156
|
+
|----|-------|------|-------------|---------------|---------------|-------------------|-------------|---------------|---------------|-------------------|---------------|
|
|
157
|
+
| A | 114.0 | 30.0 | p1 | 114.01 | 30.01 | 1470.515926 | p2 | 114.05 | 30.05 | 7351.852775 | 4411.184351 |
|
|
158
|
+
| B | 114.1 | 30.1 | p3 | 114.12 | 30.12 | 2939.507557 | p2 | 114.05 | 30.05 | 7350.037700 | 5144.772629 |
|
|
159
|
+
|
|
160
|
+
### 2. Find the nearest point for each point within the same table and add its ID, longitude, latitude, and distance.
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
import pandas as pd
|
|
164
|
+
import tablegis as tg
|
|
165
|
+
|
|
166
|
+
# Create an example DataFrame
|
|
167
|
+
df2 = pd.DataFrame({
|
|
168
|
+
'id': ['A', 'B', 'C', 'D'],
|
|
169
|
+
'lon2': [116.403, 116.407, 116.404, 116.408],
|
|
170
|
+
'lat2': [39.914, 39.918, 39.916, 39.919]
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
# Calculate the nearest 1 point
|
|
174
|
+
result = tg.min_distance_onetable(df2, 'lon2', 'lat2', idname='id', n=1)
|
|
175
|
+
# Calculate the nearest 2 points
|
|
176
|
+
result2 = tg.min_distance_onetable(df2, 'lon2', 'lat2', idname='id', n=2)
|
|
177
|
+
|
|
178
|
+
print("\nExample result (distance in meters):")
|
|
179
|
+
print(result)
|
|
180
|
+
print(result2)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
**Result Display:**
|
|
184
|
+
|
|
185
|
+
**Table df2:**
|
|
186
|
+
|
|
187
|
+
| id | lon2 | lat2 |
|
|
188
|
+
|----|--------|-------|
|
|
189
|
+
| p1 | 114.01 | 30.01 |
|
|
190
|
+
| p2 | 114.05 | 30.05 |
|
|
191
|
+
| p3 | 114.12 | 30.12 |
|
|
192
|
+
|
|
193
|
+
**Nearest 1 point:**
|
|
194
|
+
|
|
195
|
+
| | id | lon2 | lat2 | nearest1_id | nearest1_lon2 | nearest1_lat2 | nearest1_distance |
|
|
196
|
+
|---:|----|--------|-------|-------------|---------------|---------------|-------------------|
|
|
197
|
+
| 0 | p1 | 114.01 | 30.01 | p2 | 114.05 | 30.05 | 5881.336911 |
|
|
198
|
+
| 1 | p2 | 114.05 | 30.05 | p1 | 114.01 | 30.01 | 5881.336911 |
|
|
199
|
+
| 2 | p3 | 114.12 | 30.12 | p2 | 114.05 | 30.05 | 10289.545038 |
|
|
200
|
+
|
|
201
|
+
**Nearest 2 points:**
|
|
202
|
+
|
|
203
|
+
| | id | lon2 | lat2 | nearest1_id | nearest1_lon2 | nearest1_lat2 | nearest1_distance | nearest2_id | nearest2_lon2 | nearest2_lat2 | nearest2_distance | mean_distance |
|
|
204
|
+
|---:|----|--------|-------|-------------|---------------|---------------|-------------------|-------------|---------------|---------------|-------------------|---------------|
|
|
205
|
+
| 0 | p1 | 114.01 | 30.01 | p2 | 114.05 | 30.05 | 5881.336911 | p3 | 114.12 | 30.12 | 16170.880987 | 11026.108949 |
|
|
206
|
+
| 1 | p2 | 114.05 | 30.05 | p1 | 114.01 | 30.01 | 5881.336911 | p3 | 114.12 | 30.12 | 10289.545038 | 8085.440974 |
|
|
207
|
+
| 2 | p3 | 114.12 | 30.12 | p2 | 114.05 | 30.05 | 10289.545038 | p1 | 114.01 | 30.01 | 16170.880987 | 13230.213012 |
|
|
208
|
+
|
|
209
|
+
## Contributing
|
|
210
|
+
|
|
211
|
+
Contributions in all forms are welcome, including feature requests, bug reports, and code contributions.
|
|
212
|
+
|
|
213
|
+
## License
|
|
214
|
+
|
|
215
|
+
This project is licensed under the MIT License.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
tablegis/__init__.py,sha256=0XZiNvhfqAggcgJK-PeWB_Q14AL_Gc87U_fa2H3nK4M,778
|
|
2
|
+
tablegis/core.py,sha256=21OpPxJSwNNowcan_TNVuEdnGJjiSBZ4TvDDwZOGACg,10851
|
|
3
|
+
tablegis/utils.py,sha256=vUU--Bv543PdDAoRPYvdc01-cIHMRpU3TduyYaPl4Fk,3139
|
|
4
|
+
tablegis-0.0.1.dist-info/licenses/LICENSE,sha256=Couq5APCnJqi5B2aFOb_lMao7HVFe1v1LuWY7Clssns,1093
|
|
5
|
+
tablegis-0.0.1.dist-info/METADATA,sha256=HsOh7B90zMWPGunutoOtDuazs0Y7lP6iV0A8iTtUXsk,8644
|
|
6
|
+
tablegis-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
7
|
+
tablegis-0.0.1.dist-info/top_level.txt,sha256=ASW5eVRp0owVY307HKUZ61r_yIi9hIjrUu_2DoTxymM,9
|
|
8
|
+
tablegis-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Non-existent987
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tablegis
|