gov_commodity_zhejiang_country.py 7.8 KB

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