gov_commodity_zhejiang_country.py 7.4 KB

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