如何在Pandas中利用邻近网格经纬度计算并替换土壤湿度值
替换土壤湿度值为邻近网格均值的实现方法
1. 导入必要库
import pandas as pd import numpy as np import glob
2. 加载并合并所有CSV数据
先把glob获取到的所有CSV文件合并成一个统一的DataFrame:
# 替换为你的根文件夹路径,递归获取所有CSV文件 csv_files = glob.glob('你的根文件夹路径/**/*.csv', recursive=True) # 逐个加载文件并合并 df_list = [] for file in csv_files: temp_df = pd.read_csv(file) df_list.append(temp_df) merged_df = pd.concat(df_list, ignore_index=True)
确保你的数据列名包含Lat、Long、date和Soil moisture,如果列名不一致,要对应修改后续代码里的列名。
3. 构建经纬度到土壤湿度的映射
为了快速查找任意经纬度对应的湿度值,把经纬度设为索引并转成字典:
# 以经纬度为键,土壤湿度为值,构建快速查找映射 humidity_map = merged_df.set_index(['Long', 'Lat'])['Soil moisture'].to_dict() # 用round处理浮点精度问题,避免因小数位数差异导致查找失败 humidity_map = {(round(lon,2), round(lat,2)): val for (lon, lat), val in humidity_map.items()}
4. 定义邻近均值计算函数
严格按照你给出的示例逻辑,取同纬度、经度减0.05和同经度、纬度±0.05的两个邻近点均值(可根据实际网格方向调整):
def calc_neighbor_avg(longitude, latitude): neighbors = [] # 西向邻近点:经度减0.05,纬度不变 west_point = (round(longitude - 0.05, 2), round(latitude, 2)) if west_point in humidity_map: neighbors.append(humidity_map[west_point]) # 根据示例,第一个点取纬度加0.05,第二个点取纬度减0.05,这里统一检查上下两个方向 north_point = (round(longitude, 2), round(latitude + 0.05, 2)) south_point = (round(longitude, 2), round(latitude - 0.05, 2)) if north_point in humidity_map: neighbors.append(humidity_map[north_point]) if south_point in humidity_map: neighbors.append(humidity_map[south_point]) # 按示例取两个点的均值,若只有一个有效点则用该点值,无有效点则保留原值1 if len(neighbors) >= 2: return np.mean(neighbors[:2]) elif len(neighbors) == 1: return neighbors[0] else: return 1
5. 替换土壤湿度为1的数值
遍历所有符合条件的行,替换为计算出的邻近均值:
# 定位土壤湿度为1的行,调用函数替换值 merged_df.loc[merged_df['Soil moisture'] == 1, 'Soil moisture'] = merged_df.apply( lambda row: calc_neighbor_avg(row['Long'], row['Lat']), axis=1 )
6. 保存处理后的数据
把处理完成的数据集导出为新CSV:
merged_df.to_csv('处理后的土壤湿度数据.csv', index=False)
内容的提问来源于stack exchange,提问作者Faysal Kabir Shuvo
相关产品推荐
相关产品推荐

