Counter.py 2.4 KB

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