设计(二)mysql+django+echarts

1、把数据从 mysql 数据库中提取出来,然后通过 django 后台代码的处理,利用 echarts 可视化到前端

from django.shortcuts import render
import pymysql
import pandas as pd
import numpy as np

conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='secondary', charset='utf8')
sql_query = 'SELECT * FROM secondary.deal_re_2'
df = pd.read_sql(sql_query, con=conn)

# 字符串->datetime64[ns]
df['deal_time'] = pd.to_datetime(df['deal_time'])

# object - > int
# to_numeric
# 使用to_numeric()函数,告诉其将任何无效数据转换为NaN
df['through_nums'] = pd.to_numeric(df['through_nums'],errors='coerce')
# 删除through_nums 为空的行
df.dropna(subset = ['through_nums'], inplace = True)

# 使用to_numeric()函数,告诉其将任何无效数据转换为NaN
df['area'] = pd.to_numeric(df['area'], errors='coerce')
# 删除through_nums 为空的行
df.dropna(subset = ['area'], inplace = True)

df['finish_age'] = pd.to_numeric(df['finish_age'], errors='coerce')
# 删除through_nums 为空的行
df.dropna(subset = ['finish_age'], inplace = True)

df['list_time'] = pd.to_datetime(df['list_time'], errors='coerce')

# print(df.info())
def rows_row(arrays):
    list_name = []
    for row in arrays:
        list_name.append(row)
    return list_name

def rows_row_num(arrays):
    list_name = []
    for row in arrays:
        row = round(row, 2)
        list_name.append(row)
    return list_name

def list_json_list(rows1,rows2):
    list_name = []
    for i in range(len(rows1)):
        row = {'value': int(rows1[i]), 'name': rows2[i]}
        list_name.append(row)
    return list_name

def home(request):
    rows_price = df.groupby(['region_1_name'])['deal_price'].apply(np.mean)
    deal_name = rows_price.index
    rows_sum = df.groupby(['region_1_name'])['through_nums'].apply(np.sum)
    rows_name = rows_sum.index

    info = {
        'rows_price': rows_row_num(rows_price),
        'deal_name': rows_row(deal_name),
        'pie_data': list_json_list(rows_sum,rows_name),
    }

    return render(request, 'home.html', info)

# 使用完后记得关掉
conn.close()

 

posted @ 2021-04-08 21:56  天宇爱水  阅读(461)  评论(0编辑  收藏  举报