panda_util.py 3.1 KB

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