panda_util.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from mysql_db import MysqlDB
  2. class PandaUtil(object):
  3. def __init__(self, db_name):
  4. self.con = MysqlDB(db_name, db_type=1).con
  5. pass
  6. def query_data(self, sql):
  7. df = pd.read_sql_query(sql, self.con)
  8. return df
  9. def panda_chart(self, df_list, cols, title_x, title_y, file_name):
  10. """
  11. data of narray
  12. index of data_frame: [0,1,2,3]
  13. cols numbers of static columns
  14. """
  15. writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
  16. for i, df in enumerate(df_list):
  17. # df = pd.DataFrame(data, index=None, columns=["姓名", "饱和度", "人力"])
  18. sheet_name = f'Sheet{i}'
  19. df.to_excel(writer, sheet_name=sheet_name, index=False)
  20. workbook = writer.book
  21. worksheet = writer.sheets[sheet_name]
  22. chart = workbook.add_chart({'type': 'column'})
  23. # set colors for the chart each type .
  24. colors = ['#E41A1C', '#377EB8', '#4DAF4A', '#984EA3', '#FF7F00', '#7CFC00', ' #76EEC6', '#7EC0EE', '#00F5FF']
  25. # Configure the series of the chart from the dataframe data.
  26. for col_num in range(1, cols + 1):
  27. chart.add_series({
  28. 'name': [f'{sheet_name}', 0, col_num],
  29. 'categories': [f'{sheet_name}', 1, 0, 4, 0], # axis_x start row ,start col,end row ,end col
  30. 'values': [f'{sheet_name}', 1, col_num, 4, col_num], # axis_y value of
  31. 'fill': {'color': colors[col_num - 1]}, # each type color choose
  32. 'overlap': -10,
  33. })
  34. # Configure the chart axes.
  35. chart.set_x_axis({'name': f'{title_x}'})
  36. chart.set_y_axis({'name': f'{title_y}', 'major_gridlines': {'visible': False}})
  37. chart.set_size({'width': 900, 'height': 400})
  38. # Insert the chart into the worksheet.
  39. worksheet.insert_chart('H2', chart)
  40. writer.save()
  41. writer.save()
  42. if __name__ == '__main__':
  43. # pdu = PandaUtil('linshi')
  44. # sql = 'select house_id, COUNT(house_id) as number from t_house_image group by house_id limit 5'
  45. # df_data = pdu.query_data(sql)
  46. # print(df_data.size)
  47. # pdu.panda_chart([df_data], 1, 'title x', 'title y', 'pandas_chart_columns2.xlsx')
  48. # send_email = EmailUtil()
  49. # send_email.send_mail(mail_excel='pandas_chart_columns2.xlsx')
  50. import pandas as pd
  51. import numpy as np
  52. df = pd.DataFrame({'ID': [1, 2, 3, None, 5, 6, 7, 8, 9, 10],
  53. 'Name': ['Tim', 'Victor', 'Nick', None, 45, 48, '哈哈', '嗯呢', 'ess', 'dss'],
  54. 'address': ['美国', '试试', '单独', None, '刚刚', '信息', '报表', '公司', '是否', '是否'],
  55. 'address': ['美国', '试试', '单独', None, '刚刚', '信息', '报表', '公司', '是否', '是否'],
  56. 'address': ['美国', '试试', '单独', None, '刚刚', '信息', '报表', '公司', '是否', '是否']
  57. }
  58. )
  59. df.set_index("ID")
  60. df.to_excel('output.xlsx')