pv_youxiaoxing.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import multiprocessing
  2. from os import *
  3. import matplotlib
  4. matplotlib.use('Agg')
  5. matplotlib.rcParams['font.family'] = 'SimHei' # 或者 'Microsoft YaHei'
  6. matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 或者 ['Microsoft YaHei']
  7. import chardet
  8. import warnings
  9. warnings.filterwarnings("ignore")
  10. import datetime
  11. import pandas as pd
  12. def get_time_space(df, time_str):
  13. """
  14. :return: 查询时间间隔
  15. """
  16. begin = datetime.datetime.now()
  17. df1 = pd.DataFrame(df[time_str])
  18. df1[time_str] = pd.to_datetime(df1[time_str], errors='coerce')
  19. df1.sort_values(by=time_str, inplace=True)
  20. df1['chazhi'] = df1[time_str].shift(-1) - df1[time_str]
  21. result = df1.sample(int(df1.shape[0] / 100))['chazhi'].value_counts().idxmax().seconds
  22. del df1
  23. print(datetime.datetime.now() - begin)
  24. return abs(result)
  25. def get_time_space_count(start_time: datetime.datetime, end_time: datetime.datetime, time_space=1):
  26. """
  27. 获取俩个时间之间的个数
  28. :return: 查询时间间隔
  29. """
  30. delta = end_time - start_time
  31. total_seconds = delta.days * 24 * 60 * 60 + delta.seconds
  32. return abs(int(total_seconds / time_space)) + 1
  33. # 获取文件编码
  34. def detect_file_encoding(filename):
  35. # 读取文件的前1000个字节(足够用于大多数编码检测)
  36. with open(filename, 'rb') as f:
  37. rawdata = f.read(1000)
  38. result = chardet.detect(rawdata)
  39. encoding = result['encoding']
  40. if encoding is None:
  41. encoding = 'gb18030'
  42. if encoding and encoding.lower() == 'gb2312' or encoding.lower().startswith("windows"):
  43. encoding = 'gb18030'
  44. return encoding
  45. def del_blank(df=pd.DataFrame(), cols=list()):
  46. for col in cols:
  47. if df[col].dtype == object:
  48. df[col] = df[col].str.strip()
  49. return df
  50. # 切割数组到多个数组
  51. def split_array(array, num):
  52. return [array[i:i + num] for i in range(0, len(array), num)]
  53. # 读取数据到df
  54. def read_file_to_df(file_path, read_cols=list(), header=0):
  55. try:
  56. df = pd.DataFrame()
  57. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  58. encoding = detect_file_encoding(file_path)
  59. end_with_gz = str(file_path).lower().endswith("gz")
  60. if read_cols:
  61. if end_with_gz:
  62. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, compression='gzip', header=header)
  63. else:
  64. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, header=header,
  65. on_bad_lines='warn')
  66. else:
  67. if end_with_gz:
  68. df = pd.read_csv(file_path, encoding=encoding, compression='gzip', header=header)
  69. else:
  70. df = pd.read_csv(file_path, encoding=encoding, header=header, on_bad_lines='warn')
  71. else:
  72. xls = pd.ExcelFile(file_path)
  73. # 获取所有的sheet名称
  74. sheet_names = xls.sheet_names
  75. for sheet in sheet_names:
  76. if read_cols:
  77. now_df = pd.read_excel(xls, sheet_name=sheet, header=header, usecols=read_cols)
  78. else:
  79. now_df = pd.read_excel(xls, sheet_name=sheet, header=header)
  80. df = pd.concat([df, now_df])
  81. print('文件读取成功', file_path, '文件数量', df.shape)
  82. except Exception as e:
  83. print('读取文件出错', file_path, str(e))
  84. message = '文件:' + path.basename(file_path) + ',' + str(e)
  85. raise ValueError(message)
  86. return df
  87. def __build_directory_dict(directory_dict, path, filter_types=None):
  88. # 遍历目录下的所有项
  89. for item in listdir(path):
  90. item_path = path.join(path, item)
  91. if path.isdir(item_path):
  92. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  93. elif path.isfile(item_path):
  94. if path not in directory_dict:
  95. directory_dict[path] = []
  96. if filter_types is None or len(filter_types) == 0:
  97. directory_dict[path].append(item_path)
  98. elif str(item_path).split(".")[-1] in filter_types:
  99. if str(item_path).count("~$") == 0:
  100. directory_dict[path].append(item_path)
  101. # 读取所有文件
  102. # 读取路径下所有的excel文件
  103. def read_excel_files(read_path):
  104. directory_dict = {}
  105. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  106. return [path for paths in directory_dict.values() for path in paths if path]
  107. # 创建路径
  108. def create_file_path(path, is_file_path=False):
  109. if is_file_path:
  110. path = path.dirname(path)
  111. if not path.exists(path):
  112. makedirs(path, exist_ok=True)
  113. def time_biaozhun(df):
  114. time_space = get_time_space(df, '时间')
  115. query_df = df[['时间']]
  116. query_df['时间'] = pd.to_datetime(df['时间'], errors="coerce")
  117. query_df = query_df.dropna(subset=['时间'])
  118. total = get_time_space_count(query_df['时间'].min(), query_df['时间'].max(), time_space)
  119. return total, save_percent(1 - query_df.shape[0] / total), save_percent(1 - df.shape[0] / total)
  120. def save_percent(value, save_decimal=7):
  121. return round(value, save_decimal) * 100
  122. def calc(df, file_name):
  123. error_dict = {}
  124. lose_dict = {}
  125. error_dict['箱变'] = "".join(file_name.split(".")[:-1])
  126. lose_dict['箱变'] = "".join(file_name.split(".")[:-1])
  127. total, lose_time, error_time = time_biaozhun(df)
  128. error_dict['时间'] = error_time
  129. lose_dict['时间'] = lose_time
  130. error_df = pd.DataFrame()
  131. lose_df = pd.DataFrame()
  132. try:
  133. df.columns = ["".join(["逆变器" + "".join(col.split("逆变器")[1:])]) if col.find("逆变器") > -1 else col for col in
  134. df.columns]
  135. for col in df.columns:
  136. if col == '时间':
  137. continue
  138. query_df = df[[col]]
  139. query_df[col] = pd.to_numeric(query_df[col], errors="coerce")
  140. query_df = query_df.dropna(subset=[col])
  141. lose_dict[col] = save_percent(1 - query_df.shape[0] / total)
  142. if col.find('电压') > -1:
  143. error_dict[col] = save_percent(query_df[query_df[col] < 0].shape[0] / total)
  144. if col.find('电流') > -1:
  145. error_dict[col] = save_percent(query_df[query_df[col] < -0.1].shape[0] / total)
  146. if col.find('逆变器效率') > -1:
  147. error_dict[col] = save_percent(query_df[(query_df[col] <= 0) | (query_df[col] >= 100)].shape[0] / total)
  148. if col.find('温度') > -1:
  149. error_dict[col] = save_percent(query_df[(query_df[col] < 0) | (query_df[col] > 100)].shape[0] / total)
  150. if col.find('功率因数') > -1:
  151. error_dict[col] = save_percent(query_df[(query_df[col] < 0) | (query_df[col] > 1)].shape[0] / total)
  152. total, count = 0, 0
  153. for k, v in error_dict.items():
  154. if k != '箱变':
  155. total = total + error_dict[k]
  156. count = count + 1
  157. error_dict['平均异常率'] = save_percent(total / count / 100)
  158. total, count = 0, 0
  159. for k, v in lose_dict.items():
  160. if k != '箱变':
  161. total = total + lose_dict[k]
  162. count = count + 1
  163. lose_dict['平均缺失率'] = save_percent(total / count / 100)
  164. error_df = pd.concat([error_df, pd.DataFrame(error_dict, index=[0])])
  165. lose_df = pd.concat([lose_df, pd.DataFrame(lose_dict, index=[0])])
  166. error_df_cols = ['箱变', '平均异常率']
  167. for col in error_df.columns:
  168. if col not in error_df_cols:
  169. error_df_cols.append(col)
  170. lose_df_cols = ['箱变', '平均缺失率']
  171. for col in lose_df.columns:
  172. if col not in lose_df_cols:
  173. lose_df_cols.append(col)
  174. error_df = error_df[error_df_cols]
  175. lose_df = lose_df[lose_df_cols]
  176. except Exception as e:
  177. print("异常文件", path.basename(file_name))
  178. raise e
  179. return error_df, lose_df
  180. def run(file_path):
  181. df = read_file_to_df(file_path)
  182. return calc(df, path.basename(file_path))
  183. if __name__ == '__main__':
  184. # read_path = r'/data/download/大唐玉湖性能分析离线分析/05整理数据/逆变器数据'
  185. # save_path = r'/data/download/大唐玉湖性能分析离线分析/06整理数据/逆变器数据'
  186. read_path = r'D:\trans_data\大唐玉湖性能分析离线分析\test\yuanshi'
  187. save_path = r'D:\trans_data\大唐玉湖性能分析离线分析\test\zhengli'
  188. all_files = read_excel_files(read_path)
  189. with multiprocessing.Pool(2) as pool:
  190. df_arrys = pool.starmap(run, [(file,) for file in all_files])
  191. error_df = pd.concat([df[0] for df in df_arrys])
  192. lose_df = pd.concat([df[1] for df in df_arrys])
  193. with pd.ExcelWriter(path.join(save_path, "玉湖光伏数据统计.xlsx")) as writer:
  194. error_df.to_excel(writer, sheet_name='error_percent', index=False)
  195. lose_df.to_excel(writer, sheet_name='lose_percent', index=False)