result_validate.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import os
  2. import datetime
  3. import pandas as pd
  4. from data_loader import mongo_con_parse, validate_one_line, fill_hourly_crawl_date
  5. def validate_process(node, pred_time_str):
  6. date = pred_time_str[4:8]
  7. output_dir = f"./validate/{node}_{date}"
  8. os.makedirs(output_dir, exist_ok=True)
  9. object_dir = "./predictions"
  10. csv_file = f'future_predictions_{pred_time_str}.csv'
  11. csv_path = os.path.join(object_dir, csv_file)
  12. try:
  13. df_predict = pd.read_csv(csv_path)
  14. except Exception as e:
  15. print(f"read {csv_path} error: {str(e)}")
  16. df_predict = pd.DataFrame()
  17. if df_predict.empty:
  18. print(f"预测数据为空")
  19. return
  20. # fly_day = df_predict['flight_day'].unique()[0]
  21. client, db = mongo_con_parse()
  22. count = 0
  23. for idx, row in df_predict.iterrows():
  24. city_pair = row['city_pair']
  25. flight_day = row['flight_day']
  26. flight_number_1 = row['flight_number_1']
  27. flight_number_2 = row['flight_number_2']
  28. baggage = row['baggage']
  29. valid_begin_hour = row['valid_begin_hour']
  30. df_val= validate_one_line(db, city_pair, flight_day, flight_number_1, flight_number_2, baggage, valid_begin_hour)
  31. # 有可能在当前验证时刻,数据库里没有在valid_begin_hour之后的数据
  32. if not df_val.empty:
  33. df_val_f = fill_hourly_crawl_date(df_val, rear_fill=2)
  34. df_val_f = df_val_f[df_val_f['is_filled']==0] # 只要原始数据,不要补齐的
  35. if df_val_f.empty:
  36. drop_flag = 0
  37. first_drop_amount = pd.NA
  38. first_drop_hours = pd.NA
  39. last_hours_util = pd.NA
  40. last_update_hour = pd.NA
  41. list_change_price = []
  42. list_change_hours = []
  43. else:
  44. # 有效数据的最后一行
  45. last_row = df_val_f.iloc[-1]
  46. last_hours_util = last_row['hours_until_departure']
  47. last_update_hour = last_row['update_hour']
  48. # 价格变化过滤
  49. df_price_changes = df_val_f.loc[
  50. df_val_f["adult_total_price"].shift() != df_val_f["adult_total_price"]
  51. ].copy()
  52. # 价格变化幅度
  53. df_price_changes['change_amount'] = df_price_changes['adult_total_price'].diff().fillna(0)
  54. # 找到第一个 change_amount 小于 -10 的行
  55. first_negative_change = df_price_changes[df_price_changes['change_amount'] < -10].head(1)
  56. # 提取所需的值
  57. if not first_negative_change.empty:
  58. drop_flag = 1
  59. first_drop_amount = first_negative_change['change_amount'].iloc[0].round(2)
  60. first_drop_hours = first_negative_change['hours_until_departure'].iloc[0]
  61. else:
  62. drop_flag = 0
  63. first_drop_amount = pd.NA
  64. first_drop_hours = pd.NA
  65. list_change_price = df_price_changes['adult_total_price'].tolist()
  66. list_change_hours = df_price_changes['hours_until_departure'].tolist()
  67. else:
  68. drop_flag = 0
  69. first_drop_amount = pd.NA
  70. first_drop_hours = pd.NA
  71. last_hours_util = pd.NA
  72. last_update_hour = pd.NA
  73. list_change_price = []
  74. list_change_hours = []
  75. safe_sep = "; "
  76. df_predict.at[idx, 'change_prices'] = safe_sep.join(map(str, list_change_price))
  77. df_predict.at[idx, 'change_hours'] = safe_sep.join(map(str, list_change_hours))
  78. df_predict.at[idx, 'last_hours_util'] = last_hours_util
  79. df_predict.at[idx, 'last_update_hour'] = last_update_hour
  80. df_predict.at[idx, 'first_drop_amount'] = first_drop_amount * -1 # 负数转正数
  81. df_predict.at[idx, 'first_drop_hours'] = first_drop_hours
  82. df_predict.at[idx, 'drop_flag'] = drop_flag
  83. count += 1
  84. if count % 5 == 0:
  85. print(f"cal count: {count}")
  86. print(f"计算结束")
  87. client.close()
  88. timestamp_str = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  89. save_scv = f"result_validate_{node}_{pred_time_str}_{timestamp_str}.csv"
  90. output_path = os.path.join(output_dir, save_scv)
  91. df_predict.to_csv(output_path, index=False, encoding="utf-8-sig")
  92. print(f"保存完成: {output_path}")
  93. if __name__ == "__main__":
  94. node, pred_time_str = "node0108", "202601121000"
  95. validate_process(node, pred_time_str)