玉湖光伏-气象标准化.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 9 16:28:48 2024
  4. @author: Administrator
  5. """
  6. import multiprocessing
  7. import os
  8. from datetime import datetime, timedelta
  9. import numpy as np
  10. import pandas as pd
  11. import chardet
  12. pd.options.mode.copy_on_write = True
  13. # 获取文件编码
  14. def detect_file_encoding(filename):
  15. # 读取文件的前1000个字节(足够用于大多数编码检测)
  16. with open(filename, 'rb') as f:
  17. rawdata = f.read(1000)
  18. result = chardet.detect(rawdata)
  19. encoding = result['encoding']
  20. if encoding is None:
  21. encoding = 'gb18030'
  22. if encoding and encoding.lower() == 'gb2312' or encoding.lower().startswith("windows"):
  23. encoding = 'gb18030'
  24. return encoding
  25. # 读取数据到df
  26. def read_file_to_df(file_path, read_cols=list(), header=0):
  27. df = pd.DataFrame()
  28. if str(file_path).lower().endswith("csv") or str(file_path).lower().endswith("gz"):
  29. encoding = detect_file_encoding(file_path)
  30. end_with_gz = str(file_path).lower().endswith("gz")
  31. if read_cols:
  32. if end_with_gz:
  33. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, compression='gzip', header=header)
  34. else:
  35. df = pd.read_csv(file_path, encoding=encoding, usecols=read_cols, header=header, on_bad_lines='warn')
  36. else:
  37. if end_with_gz:
  38. df = pd.read_csv(file_path, encoding=encoding, compression='gzip', header=header)
  39. else:
  40. df = pd.read_csv(file_path, encoding=encoding, header=header, on_bad_lines='warn')
  41. else:
  42. xls = pd.ExcelFile(file_path)
  43. # 获取所有的sheet名称
  44. sheet_names = xls.sheet_names
  45. for sheet in sheet_names:
  46. if read_cols:
  47. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, header=header, usecols=read_cols)])
  48. else:
  49. df = pd.concat([df, pd.read_excel(xls, sheet_name=sheet, header=header)])
  50. return df
  51. def __build_directory_dict(directory_dict, path, filter_types=None):
  52. # 遍历目录下的所有项
  53. for item in os.listdir(path):
  54. item_path = os.path.join(path, item)
  55. if os.path.isdir(item_path):
  56. __build_directory_dict(directory_dict, item_path, filter_types=filter_types)
  57. elif os.path.isfile(item_path):
  58. if path not in directory_dict:
  59. directory_dict[path] = []
  60. if filter_types is None or len(filter_types) == 0:
  61. directory_dict[path].append(item_path)
  62. elif str(item_path).split(".")[-1] in filter_types:
  63. if str(item_path).count("~$") == 0:
  64. directory_dict[path].append(item_path)
  65. # 读取所有文件
  66. # 读取路径下所有的excel文件
  67. def read_excel_files(read_path):
  68. directory_dict = {}
  69. __build_directory_dict(directory_dict, read_path, filter_types=['xls', 'xlsx', 'csv', 'gz'])
  70. return [path for paths in directory_dict.values() for path in paths if path]
  71. # 创建路径
  72. def create_file_path(path, is_file_path=False):
  73. if is_file_path:
  74. path = os.path.dirname(path)
  75. if not os.path.exists(path):
  76. os.makedirs(path, exist_ok=True)
  77. if __name__ == '__main__':
  78. # path = r'/data/download/大唐玉湖性能分析离线分析/05整理数据/气象站数据'
  79. # save_path = r'/data/download/大唐玉湖性能分析离线分析/06整理数据/气象站数据'
  80. path = r'Z:\大唐玉湖性能分析离线分析\05整理数据\气象站数据'
  81. save_path = r'Z:\大唐玉湖性能分析离线分析\06整理数据\气象站数据'
  82. fengsu_df = read_file_to_df(os.path.join(path, '风速.csv'), read_cols=['当前时间', '实际风速'])
  83. fengxiang_df = read_file_to_df(os.path.join(path, '风向.csv'), read_cols=['当前时间', '实际风向'])
  84. fuzhaodu_df = read_file_to_df(os.path.join(path, '辐照度.csv'), read_cols=['时间', '水平总辐照度', '倾斜总辐照度', '散射辐照度'])
  85. shidu_df = read_file_to_df(os.path.join(path, '湿度.csv'), read_cols=['时间', '实际湿度'])
  86. wendu_df = read_file_to_df(os.path.join(path, '温度.csv'), read_cols=['时间', '实际温度'])
  87. yali_df = read_file_to_df(os.path.join(path, '压力.csv'), read_cols=['时间', '实际气压'])
  88. fengsu_df.rename(columns={'当前时间': '时间'}, inplace=True)
  89. fengxiang_df.rename(columns={'当前时间': '时间'}, inplace=True)
  90. dfs = [fengxiang_df, fengsu_df, fuzhaodu_df, shidu_df, wendu_df, yali_df]
  91. for df in dfs:
  92. df['时间'] = pd.to_datetime(df['时间'])
  93. df.set_index(keys='时间', inplace=True)
  94. df = pd.concat(dfs, axis=1)
  95. create_file_path(save_path, is_file_path=False)
  96. df.to_csv(os.path.join(save_path, '气象合并.csv'), encoding='utf-8')