organize_xinhua_files_data.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import datetime
  2. import multiprocessing
  3. import warnings
  4. from os import *
  5. import pandas as pd
  6. warnings.filterwarnings("ignore")
  7. def __build_directory_dict(directory_dict, path, filter_types=None):
  8. # 遍历目录下的所有项
  9. for item in listdir(path):
  10. item_path = path.join(path, item)
  11. if path.isdir(item_path):
  12. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  13. elif path.isfile(item_path):
  14. if path not in directory_dict:
  15. directory_dict[path] = []
  16. if filter_types is None or len(filter_types) == 0:
  17. directory_dict[path].append(item_path)
  18. elif str(item_path).split(".")[-1] in filter_types:
  19. if str(item_path).count("~$") == 0:
  20. directory_dict[path].append(item_path)
  21. # 读取路径下所有的excel文件
  22. def read_excel_files(read_path):
  23. if path.isfile(read_path):
  24. return [read_path]
  25. directory_dict = {}
  26. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  27. return [path for paths in directory_dict.values() for path in paths if path]
  28. # 创建路径
  29. def create_file_path(path, is_file_path=False):
  30. """
  31. 创建路径
  32. :param path:创建文件夹的路径
  33. :param is_file_path: 传入的path是否包含具体的文件名
  34. """
  35. if is_file_path:
  36. path = path.dirname(path)
  37. if not path.exists(path):
  38. makedirs(path, exist_ok=True)
  39. def boolean_is_check_data(df_cols, need_valid=True):
  40. if not need_valid:
  41. return True
  42. fault_list = ['快速停机', '故障名称', '故障代码', '故障停机', '人工停机', '风机紧急停机', '风机自身故障停机', '限功率运行状态']
  43. df_cols = [str(i).split('_')[-1] for i in df_cols]
  44. for fault in fault_list:
  45. if fault in df_cols:
  46. return True
  47. return False
  48. def read_fle_to_df(file_path):
  49. df = pd.read_excel(file_path)
  50. wind_name = [i for i in df.columns if i.find('_') > -1][0].split('_')[0]
  51. df.columns = [i.split('_')[-1] for i in df.columns]
  52. df['wind_name'] = wind_name
  53. df['采样时间'] = pd.to_datetime(df['采样时间'])
  54. df['采样时间'] = df['采样时间'].dt.ceil('T')
  55. return boolean_is_check_data(df.columns, file_path.find('批次') > -1), wind_name, df
  56. def read_guzhangbaojing(file_path):
  57. try:
  58. df = pd.read_excel(file_path)
  59. df.rename(columns={'风机名': 'wind_name'}, inplace=True)
  60. df['采样时间'] = pd.to_datetime(df['采样时间'])
  61. df['采样时间'] = df['采样时间'].dt.ceil('T')
  62. df = df[(df['采样时间'] >= '2024-08-01 00:00:00') & (df['采样时间'] < '2024-10-01 00:00:00')]
  63. return df
  64. except Exception as e:
  65. print(file_path, e)
  66. raise e
  67. def combine_df(dfs, wind_name, save_path=''):
  68. print(wind_name)
  69. cols = list()
  70. col_map = dict()
  71. try:
  72. df = dfs[0]
  73. cols.extend(df.columns)
  74. for index, now_df in enumerate(dfs):
  75. if index > 0:
  76. for col in now_df.columns:
  77. if col in cols and col not in ['采样时间', 'wind_name']:
  78. if col in col_map.keys():
  79. count = col_map[col]
  80. col_map[col] = count + 1
  81. else:
  82. count = 1
  83. col_map[col] = 1
  84. now_df.rename(columns={col: col + '__' + str(count)}, inplace=True)
  85. df = pd.merge(df, now_df, on=['采样时间', 'wind_name'], how='outer')
  86. cols.extend(now_df.columns)
  87. except Exception as e:
  88. print(wind_name, e)
  89. raise e
  90. df.reset_index(inplace=True)
  91. df.drop_duplicates(inplace=True, subset=['采样时间', 'wind_name'])
  92. if 'index' in df.columns:
  93. del df['index']
  94. create_file_path(save_path)
  95. df.sort_values(by='采样时间', inplace=True)
  96. df.set_index(keys=['采样时间', 'wind_name'], inplace=True)
  97. return wind_name, df
  98. def sae_to_csv(wind_name, df):
  99. try:
  100. col_tuples = [(col.split('__')[0], col) for col in df.columns if col.find('__') > -1]
  101. col_dict = dict()
  102. for origin, col in col_tuples:
  103. if origin in col_dict.keys():
  104. col_dict[origin].add(col)
  105. else:
  106. col_dict[origin] = {col}
  107. for origin, cols in col_dict.items():
  108. print(wind_name, origin, cols)
  109. if pd.api.types.is_numeric_dtype(df[origin]):
  110. df[origin] = df[list(cols)].max(axis=1)
  111. else:
  112. df[origin] = df[list(cols)].apply(lambda x: [i for i in x.values if i][0], axis=1)
  113. for col in cols:
  114. if col != origin:
  115. del df[col]
  116. df.to_csv(path.join(save_path, wind_name + '.csv'), encoding='utf8')
  117. except Exception as e:
  118. print(wind_name, df.columns)
  119. raise e
  120. if __name__ == '__main__':
  121. begin = datetime.datetime.now()
  122. base_path = r'/data/download/collection_data/1进行中/新华水电/收资数据/风机SCADA数据'
  123. dir1 = base_path + r'/data'
  124. dir2 = base_path + r'/故障报警/汇能机组数据-故障'
  125. dir3 = base_path + r'/故障报警/报警'
  126. save_path = r'/data/download/collection_data/1进行中/新华水电/清理数据/合并批次1-2故障报警'
  127. create_file_path(save_path)
  128. # result_datas = [
  129. # (r'/data/download/collection_data/1进行中/新华水电/风机SCADA数据',
  130. # r'/data/download/collection_data/1进行中/新华水电/整理数据/批次1-2合并'),
  131. # ]
  132. data_wind_name = dict()
  133. files = read_excel_files(dir1)
  134. with multiprocessing.Pool(30) as pool:
  135. datas = pool.starmap(read_fle_to_df, [(file,) for file in files])
  136. for data in datas:
  137. check_data, wind_name, df = data[0], data[1], data[2]
  138. if wind_name in data_wind_name.keys():
  139. data_wind_name[wind_name].append(df)
  140. else:
  141. data_wind_name[wind_name] = [df]
  142. with multiprocessing.Pool(30) as pool:
  143. data_dfs = pool.starmap(combine_df,
  144. [(dfs, wind_name, save_path) for wind_name, dfs
  145. in
  146. data_wind_name.items()])
  147. result_data_dict = dict()
  148. for wind_name, df in data_dfs:
  149. result_data_dict[wind_name] = df
  150. for dir4 in [dir2, dir3]:
  151. guzhang_files = read_excel_files(dir4)
  152. with multiprocessing.Pool(30) as pool:
  153. guzhang_datas = pool.starmap(read_guzhangbaojing, [(file,) for file in guzhang_files])
  154. guzhang_df = pd.DataFrame()
  155. for df in guzhang_datas:
  156. if not df.empty:
  157. guzhang_df = pd.concat([guzhang_df, df])
  158. wind_names = set(list(guzhang_df['wind_name'].values))
  159. for wind_name in wind_names:
  160. now_df = guzhang_df[guzhang_df['wind_name'] == wind_name]
  161. if wind_name in result_data_dict.keys():
  162. now_df.reset_index(inplace=True)
  163. now_df.drop_duplicates(inplace=True, subset=['采样时间', 'wind_name'])
  164. if 'index' in now_df.columns:
  165. del now_df['index']
  166. now_df.sort_values(by='采样时间', inplace=True)
  167. now_df.set_index(keys=['采样时间', 'wind_name'], inplace=True)
  168. res_df = result_data_dict[wind_name]
  169. result_data_dict[wind_name] = pd.concat([res_df, now_df], axis=1)
  170. with multiprocessing.Pool(30) as pool:
  171. pool.starmap(sae_to_csv, [(wind_name, df) for wind_name, df in result_data_dict.items()])
  172. print(datetime.datetime.now() - begin)