Counter.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import os
  2. import pandas as pd
  3. from pyproj import Transformer
  4. from shapely.geometry import Point
  5. import numpy as np
  6. # 读取耕地中心点CSV文件
  7. csv_cultivated_land = r"..\Data\四县三用地&水田.csv"
  8. df_land = pd.read_csv(csv_cultivated_land)
  9. # 确保CSV文件包含必要的字段
  10. required_fields = ['中心点经度', '中心点纬度', 'DLMC']
  11. for field in required_fields:
  12. if field not in df_land.columns:
  13. raise ValueError(f"耕地CSV文件缺少必要的字段: {field}")
  14. # 筛选出旱地
  15. land_type = "旱地" # 避免使用str作为变量名,因为它是Python内置函数
  16. df_land = df_land[df_land['DLMC'] == land_type]
  17. # 定义坐标系转换(假设输入已是WGS84,根据实际情况修改)
  18. source_crs = "EPSG:4326"
  19. transformer = Transformer.from_crs(source_crs, "EPSG:4326", always_xy=True)
  20. # 读取采样点数据
  21. xls_file = r"..\Data\Irrigation_water_SamplingPoint.xlsx"
  22. df_xls = pd.read_excel(xls_file)
  23. # 设置系数
  24. A = 711 * 0.524
  25. B = 427 * 0.599
  26. C = 200 * 0.7
  27. # 根据土地类型选择系数
  28. coefficient = 0.0
  29. if land_type == "水浇地":
  30. coefficient = B
  31. elif land_type == "水田":
  32. coefficient = A
  33. else:
  34. coefficient = C
  35. # 存储结果的列表
  36. data_rows = []
  37. # 遍历耕地中心点
  38. for index, row in df_land.iterrows():
  39. # 获取正确的坐标字段
  40. lon = row['中心点经度']
  41. lat = row['中心点纬度']
  42. # 坐标转换(如果需要)
  43. if source_crs != "EPSG:4326":
  44. lon, lat = transformer.transform(lon, lat)
  45. # 创建中心点几何对象
  46. center_point = Point(lon, lat)
  47. # 计算到所有采样点的距离
  48. distances = df_xls.apply(
  49. lambda x: center_point.distance(Point(x['经度'], x['纬度'])),
  50. axis=1
  51. )
  52. # 找到最近的采样点
  53. nearest_index = distances.idxmin()
  54. nearest_sample = df_xls.loc[nearest_index]
  55. # 计算Cd值
  56. cd_value = nearest_sample['Cd (ug/L)'] * coefficient
  57. # 添加到结果列表
  58. data_rows.append({
  59. 'DLMC': row['DLMC'],
  60. '中心点经度': lon,
  61. '中心点纬度': lat,
  62. 'Cd (ug/L)': cd_value
  63. })
  64. # 创建DataFrame并选择指定列
  65. csv_data = pd.DataFrame(data_rows)
  66. # 保存结果
  67. csv_file_path = r"D:\土壤-大创\Water\Data\旱地_Cd.csv"
  68. csv_data.to_csv(csv_file_path, index=False, encoding='utf-8-sig')
  69. print(f"CSV文件已保存至: {csv_file_path}")