gov_commodity_zhejiang_country.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. from pathlib import Path
  2. import pandas as pd
  3. from zhejiang import download_dir
  4. from utils import base_country_code, base_mysql
  5. from utils.base_country_code import format_sql_value
  6. from utils.log import log
  7. # 排除地区名单
  8. EXCLUDE_REGIONS = ["亚洲", "非洲", "欧洲", "拉丁美洲", "北美洲", "大洋洲", "南极洲",
  9. "东南亚国家联盟", "欧洲联盟", "亚太经济合作组织",
  10. "区域全面经济伙伴关系协定(RCEP)成员国", "共建“一带一路”国家和地区"]
  11. def get_df_country(path, year_month):
  12. file_paths = list(Path(path).glob('*'))
  13. if not file_paths:
  14. log.info("未找到任何文件")
  15. return None
  16. file_path = file_paths[0]
  17. log.info(f"处理文件: {file_path.name}")
  18. xls = pd.ExcelFile(file_path)
  19. import_df = pd.DataFrame()
  20. export_df = pd.DataFrame()
  21. total_df = pd.DataFrame()
  22. flag = True
  23. file_path = file_paths[0]
  24. if len(file_paths) > 1:
  25. for file_path in file_paths:
  26. if '洲贸组织' in file_path.name:
  27. file_path = file_path
  28. flag = False
  29. break
  30. if flag:
  31. df = pd.read_excel(xls, sheet_name=1, header=None)
  32. else:
  33. df = pd.read_excel(file_path, header=None)
  34. temp_df = df[[0, 1]].rename(columns={0: 'commodity', 1: 'total'})
  35. temp_df['total'] = pd.to_numeric(temp_df['total'].replace('--', 0), errors='coerce').astype(float)
  36. if year_month and year_month == '2024-07':
  37. temp_df['total'] = temp_df['total'] / 10000
  38. total_df = pd.concat([total_df, temp_df])
  39. temp_df = df[[0, 2]].rename(columns={0: 'commodity', 2: 'import'})
  40. temp_df['import'] = pd.to_numeric(temp_df['import'].replace('--', 0), errors='coerce').astype(float)
  41. if year_month and year_month == '2024-07':
  42. temp_df['import'] = temp_df['import'] / 10000
  43. import_df = pd.concat([import_df, temp_df])
  44. temp_df = df[[0, 3]].rename(columns={0: 'commodity', 3: 'export'})
  45. temp_df['export'] = pd.to_numeric(temp_df['export'].replace('--', 0), errors='coerce').astype(float)
  46. if year_month and year_month == '2024-07':
  47. temp_df['export'] = temp_df['export'] / 10000
  48. export_df = pd.concat([export_df, temp_df])
  49. return import_df, export_df, total_df
  50. def process_folder(path):
  51. res = get_df_country(path, None)
  52. if not res:
  53. log.info(f"{path} 目录里文件未找到包含 国别 sheet")
  54. return
  55. import_df, export_df, total_df = res
  56. year, month = base_country_code.extract_year_month_from_path(path)
  57. year_month = f'{year}-{month:02d}'
  58. # 当月数据分组清洗
  59. curr_import = import_df.groupby('commodity')['import'].sum().reset_index()
  60. curr_export = export_df.groupby('commodity')['export'].sum().reset_index()
  61. total_df = total_df.groupby('commodity')['total'].sum().reset_index()
  62. if not month == 1:
  63. previous_month_dir = base_country_code.get_previous_month_dir(path)
  64. res = get_df_country(previous_month_dir, year_month)
  65. if not res:
  66. log.info(f"{path} 上月目录里文件未找到包含 国别 sheet")
  67. return
  68. prev_import_df, prev_export_df, prev_total_df = res
  69. # 上月数据分组
  70. prev_import = prev_import_df.groupby('commodity')['import'].sum().reset_index()
  71. prev_export = prev_export_df.groupby('commodity')['export'].sum().reset_index()
  72. prev_total_df = prev_total_df.groupby('commodity')['total'].sum().reset_index()
  73. # 差值计算
  74. curr_import = pd.merge(curr_import, prev_import, on='commodity', how='left')
  75. curr_import['import'] = round(curr_import['import_x'] - curr_import['import_y'], 4)
  76. curr_export = pd.merge(curr_export, prev_export, on='commodity', how='left')
  77. curr_export['export'] = round(curr_export['export_x'] - curr_export['export_y'], 4)
  78. total_df = pd.merge(total_df, prev_total_df, on='commodity', how='left')
  79. total_df['total'] = round(total_df['total_x'] - total_df['total_y'], 4)
  80. log.info(f"合并文件: {path}*********{previous_month_dir}")
  81. # 合并进出口数据
  82. merged_df = pd.merge(curr_import, curr_export, on='commodity', how='outer')
  83. merged_df = pd.merge(merged_df, total_df, on='commodity', how='outer')
  84. sql_arr = []
  85. # try:
  86. for _, row in merged_df.iterrows():
  87. country_name = str(row['commodity']).strip()
  88. if country_name.endswith(")") or country_name.endswith(")"):
  89. country_name = country_name.rsplit("(")[0] or country_name.rsplit("(")[0]
  90. # 过滤掉排除地区
  91. if country_name in EXCLUDE_REGIONS:
  92. continue
  93. # 获取国家编码
  94. country_code = base_country_code.COUNTRY_CODE_MAPPING.get(country_name)
  95. if not country_code:
  96. log.info(f"{year_month} 未找到国家 '{country_name}' 对应的编码")
  97. continue
  98. # 提取数据并格式化
  99. if year == 2025 or (year == 2024 and month in [7, 8, 9, 10, 11, 12]):
  100. monthly_import = round(row['import'], 4)
  101. monthly_export = round(row['export'], 4)
  102. monthly_total = round(row['total'], 4)
  103. else:
  104. monthly_import = round(row['import'] / 10000, 4)
  105. monthly_export = round(row['export'] / 10000, 4)
  106. monthly_total = round(row['total'] / 10000, 4)
  107. yoy_import_export, yoy_import, yoy_export = 0, 0, 0
  108. # 构建 SQL
  109. sql = (
  110. f"INSERT INTO t_yujin_crossborder_prov_country_trade "
  111. f"(crossborder_year, crossborder_year_month, prov_code, prov_name, country_code, country_name, "
  112. f"monthly_total, monthly_export, monthly_import, yoy_import_export, yoy_import, yoy_export, create_time) "
  113. f"VALUES ('{year}', '{year_month}', '330000', '浙江省', '{country_code}', '{country_name}', "
  114. f"{format_sql_value(monthly_total)}, {format_sql_value(monthly_export)}, {format_sql_value(monthly_import)}, '{yoy_import_export}', '{yoy_import}', "
  115. f"'{yoy_export}', NOW()) ON DUPLICATE KEY UPDATE create_time = now();"
  116. )
  117. sql_arr.append(sql)
  118. # except Exception as e:
  119. # log.info(f"{year_month} 处理时发生异常: {str(e)}")
  120. log.info(f"√ {year_month} 成功生成 SQL 条数: {len(sql_arr)}")
  121. # 批量插入数据库
  122. base_mysql.bulk_insert(sql_arr)
  123. log.info(f"√ {year_month} prov_country_trade SQL 存表完成!\n")
  124. def hierarchical_traversal(root_path):
  125. root = Path(root_path)
  126. year_dirs = [
  127. item for item in root.iterdir()
  128. if item.is_dir() and base_country_code.YEAR_PATTERN.match(item.name)
  129. ]
  130. for year_dir in sorted(year_dirs, key=lambda x: x.name, reverse=True):
  131. log.info(f"\n年份:{year_dir.name} | 省份:zhejiang")
  132. month_dirs = []
  133. for item in year_dir.iterdir():
  134. if item.is_dir() and base_country_code.MONTH_PATTERN.match(item.name):
  135. month_dirs.append({"path": item, "month": int(item.name)})
  136. if month_dirs:
  137. for md in sorted(month_dirs, key=lambda x: x["month"], reverse=True):
  138. log.info(f" 月份:{md['month']:02d} | 路径:{md['path']}")
  139. process_folder(md['path'])
  140. if __name__ == '__main__':
  141. # hierarchical_traversal(download_dir)
  142. root = Path(download_dir) / '2024' / '07'
  143. process_folder(root)
  144. log.info("浙江杭州海关国别所有文件处理完成!")