光伏箱体.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 9 16:28:48 2024
  4. @author: Administrator
  5. """
  6. import os
  7. from datetime import datetime, timedelta
  8. import pandas as pd
  9. import chardet
  10. from multiprocessing import Pool
  11. # 获取文件编码
  12. def detect_file_encoding(filename):
  13. # 读取文件的前1000个字节(足够用于大多数编码检测)
  14. with open(filename, 'rb') as f:
  15. rawdata = f.read(1000)
  16. result = chardet.detect(rawdata)
  17. encoding = result['encoding']
  18. if encoding is None:
  19. encoding = 'gb18030'
  20. if encoding and encoding.lower() == 'gb2312' or encoding.lower().startswith("windows"):
  21. encoding = 'gb18030'
  22. return encoding
  23. # 读取数据到df
  24. def read_file_to_df(file_path, read_cols=list(), header=0):
  25. df = pd.DataFrame()
  26. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  27. encoding = detect_file_encoding(file_path)
  28. end_with_gz = str(file_path).lower().endswith("gz")
  29. if read_cols:
  30. if end_with_gz:
  31. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, compression='gzip', header=header)
  32. else:
  33. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, header=header, on_bad_lines='warn')
  34. else:
  35. if end_with_gz:
  36. df = pd.read_csv(file_path, encoding=encoding, compression='gzip', header=header)
  37. else:
  38. df = pd.read_csv(file_path, encoding=encoding, header=header, on_bad_lines='warn')
  39. else:
  40. xls = pd.ExcelFile(file_path)
  41. # 获取所有的sheet名称
  42. sheet_names = xls.sheet_names
  43. for sheet in sheet_names:
  44. if read_cols:
  45. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, header=header, usecols=read_cols)])
  46. else:
  47. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, header=header)])
  48. return df
  49. def __build_directory_dict(directory_dict, path, filter_types=None):
  50. # 遍历目录下的所有项
  51. for item in os.listdir(path):
  52. item_path = os.path.join(path, item)
  53. if os.path.isdir(item_path):
  54. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  55. elif os.path.isfile(item_path):
  56. if path not in directory_dict:
  57. directory_dict[path] = []
  58. if filter_types is None or len(filter_types) == 0:
  59. directory_dict[path].append(item_path)
  60. elif str(item_path).split(".")[-1] in filter_types:
  61. if str(item_path).count("~$") == 0:
  62. directory_dict[path].append(item_path)
  63. # 读取所有文件
  64. # 读取路径下所有的excel文件
  65. def read_excel_files(read_path):
  66. directory_dict = {}
  67. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  68. return [path for paths in directory_dict.values() for path in paths if path]
  69. # 创建路径
  70. def create_file_path(path, is_file_path=False):
  71. if is_file_path:
  72. path = os.path.dirname(path)
  73. if not os.path.exists(path):
  74. os.makedirs(path, exist_ok=True)
  75. def read_and_save_csv(file_path):
  76. begin = datetime.now()
  77. base_name = os.path.basename(file_path)
  78. print('开始', base_name)
  79. df1 = read_file_to_df(file_path + "箱变(1-8号逆变器)数据1.xls")
  80. del df1['Unnamed: 0']
  81. df1['时间'] = pd.to_datetime(df1['时间'])
  82. df1.set_index(keys='时间', inplace=True)
  83. df2 = read_file_to_df(file_path + "箱变(9-16号逆变器)数据1.xls")
  84. del df2['Unnamed: 0']
  85. df2['时间'] = pd.to_datetime(df2['时间'])
  86. df2.set_index(keys='时间', inplace=True)
  87. df3 = read_file_to_df(file_path + "箱变(1-8号逆变器)数据2.xls")
  88. del df3['Unnamed: 0']
  89. df3['时间'] = pd.to_datetime(df3['时间'])
  90. df3.set_index(keys='时间', inplace=True)
  91. df4 = read_file_to_df(file_path + "箱变(9-16号逆变器)数据2.xls")
  92. del df4['Unnamed: 0']
  93. df4['时间'] = pd.to_datetime(df4['时间'])
  94. df4.set_index(keys='时间', inplace=True)
  95. df = pd.concat([df1, df2, df3, df4], axis=1)
  96. df.reset_index(inplace=True)
  97. columns = list(df.columns)
  98. columns.sort()
  99. print(df.columns)
  100. df = df[columns]
  101. df.sort_values(by='时间', inplace=True)
  102. df.to_csv(os.path.join(r'D:\trans_data\大唐玉湖性能分析离线分析', '05整理数据', base_name + '_箱变.csv'), encoding='utf-8',
  103. index=False)
  104. print('结束', base_name, '耗时:' + str(datetime.now() - begin))
  105. if __name__ == '__main__':
  106. path = r'D:\trans_data\大唐玉湖性能分析离线分析\test'
  107. all_files = read_excel_files(path)
  108. all_paths = set()
  109. for file in all_files:
  110. base_name = os.path.basename(file).split("箱变")[0]
  111. base_path = os.path.dirname(file)
  112. if base_name not in all_paths:
  113. all_paths.add(os.path.join(base_path, base_name))
  114. all_datas = list(all_paths)
  115. all_datas.sort()
  116. print(all_datas)
  117. # with Pool(1) as pool:
  118. # pool.starmap(read_and_save_csv, [(i,) for i in all_datas])