python+pandas实现数据分析功能

示例简介

本文介绍使用python语言开发一个数据分析程序,可以对导入的数据进行“提取”、“筛选”、“合并”、“排行”和“生成图表”等。

开发环境:Windows7+python3.7+pycharm2018.2.4(开发工具);

目录架构:

最终效果:

实现过程

一、抓取数据

1. 使用akshare获取数据,安装和使用可以查看https://www.akshare.xyz/zh_CN/latest/,里面有详细的示例;

2. 抓取代码如下,包括A股实时行情数据、股票指数实时行情数据和科创板实时行情数据三个文件;

import akshare as ak
# 获取A股实时行情数据
stock_zh_a_spot_df = ak.stock_zh_a_spot()
stock_zh_a_spot_df.to_excel('data\sstock_zh_a_spot_df.xlsx')

# 获取股票指数实时行情数据
stock_df = ak.stock_zh_index_spot()
stock_df.to_excel('data\stock_df.xlsx')

# 获取科创板实时行情数据
stock_zh_kcb_spot_df = ak.stock_zh_kcb_spot()
stock_zh_kcb_spot_df.to_excel('data\sstock_zh_kcb_spot_df.xlsx')

二、阅读器UI设计

1. 安装模块和配置工具,参考《python实现小说阅读器》

2. 运行工具QtDesigner,利用QtDesigner工具箱设计出界面效果(所需要的控件可查看右边区域),保存效果为文件dataAnalysis.ui;

3. 对文件dataAnalysis.ui执行pyUIC(ui转化为py代码),执行完生成文件dataAnalysis.py;

三、代码设计

1. 添加内置模块(下面代码使用)和主方法(用于运行后弹出数据分析界面);

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import qApp,QFileDialog

import sys
import pandas as pd
import os
import glob

import pyecharts.options as opts
from pyecharts.charts import Line

# 导入数据目录路径
root = ''
# 左边目录行数
rowIndex = 0
# 浏览选择的路径
tempRoot = ''
# 主方法(添加代码)
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()  # 创建窗体对象
    ui = Ui_MainWindow()  # 创建PyQt设计的窗体对象
    ui.setupUi(MainWindow)  # 调用PyQt窗体的方法对窗体对象进行初始化设置
    MainWindow.show()  # 显示窗体
    sys.exit(app.exec_())  # 程序关闭时退出进程

2. 实现点击“浏览”按钮功能;函数setupUi添加“浏览”点击触发,并添加触发函数代码,用来显示选择路径和获取选择路径;

# 单击"浏览"按钮,选择文件存储路径
self.browseButton.clicked.connect(self.browseButton_click)
# 单击“浏览”按钮选择文件存储路径
def browseButton_click(self):
    global tempRoot
    tempRoot = QFileDialog.getExistingDirectory(None, "选择文件夹", os.getcwd())
    self.filePath.setText(tempRoot)

3. 添加公共函数saveExcel,用来根据勾选的路径,把处理过的数据保存到对应的文件夹下;

# 用于保存数据到Excel
def saveExcel(df, isChecked):
    # 将提取后的数据保存到Excel
    if (isChecked): # 保存在原文件夹内
        writer = pd.ExcelWriter('myExcel.xls', engine='openpyxl')
    else: # 自定义保存文件夹
        # 使用ExcelWriter()可以向同一个excel的不同sheet中写入对应的表格数据
        writer = pd.ExcelWriter(tempRoot + '/myExcel.xls', engine='openpyxl')
    df.to_excel(writer, 'sheet1')
    writer.save()

4. 实现点击“退出”按钮退出系统功能,只需在函数setupUi添加下面代码;

# 单击工具栏“退出”按钮退出程序
self.exitButton.triggered.connect(qApp.quit)

5. 实现点击“导入数据”按钮左边显示文件夹下的文件,点击左边文件右边显示文件的内容;

1)函数setupUi添加“导入数据”点击触发;并添加触发函数代码,用来显示选择文件夹下面的文件;

self.importButton.triggered.connect(self.showFile)
# 点击导入数据
def showFile(self):
    # 文件夹路径
    global root
    root = QFileDialog.getExistingDirectory(None, "选择文件夹", os.getcwd())
    mylist = []
    # 遍历文件夹文件
    for dirpath, dirnames, filenames in os.walk(root):
        for filepath in filenames:
            mylist.append(os.path.join(filepath))
    # 实例化列表模型,添加数据列表
    self.model = QtCore.QStringListModel()
    # 添加列表数据
    self.model.setStringList(mylist)
    self.leftList.setModel(self.model)
    self.leftList = mylist

2)函数setupUi添加左边文件点击触发;并添加触发函数代码,用来显示左边点击文件的数据;

# 单击QListView列表触发自定义函数
self.leftList.clicked.connect(self.showData)
# 设置Dataframe对象显示所有列
pd.set_option('display.max_columns', None)
# 设置Dataframe对象列宽为200,默认为50
pd.set_option('max_colwidth', 200)
# 单击左侧文件右侧显示数据
def showData(self, qModelIndex):
    global rowIndex
    rowIndex = qModelIndex.row()
    # 获取当前选中行的数据
    a = root + '/' + str(self.leftList[rowIndex])
    print(root)
    df = pd.DataFrame(pd.read_excel(a, engine='openpyxl'))
    # 缺失数据填充(0)
    df = df.fillna(0)
    # 重复数据处理保留第一个
    df = df.drop_duplicates(subset='name')

    self.dataArea.setText(str(df))

6. 实现点击“提取数据”按钮功能;函数setupUi添加“提取数据”点击触发,并添加触发函数代码,用来提取列“code”、“name”、“trade”和“ticktime”的数据;

self.extractButton.triggered.connect(self.extractData)
# 提取列数据
def extractData(self):
    if root:  # 导入数据才能处理
        # 获取当前选中行的数据
        a = root + '/' + str(self.leftList[rowIndex])
        df = pd.DataFrame(pd.read_excel(a, engine='openpyxl'))
        # 显示指定列数据
        df = df[['code', 'name', 'trade', 'ticktime']]
        self.dataArea.setText(str(df))
        # 保存数据到Excel
        saveExcel(df, self.rButton1.isChecked())

7. 实现点击“定向筛选”按钮功能;函数setupUi添加“定向筛选”点击触发,并添加触发函数代码,用来筛选“同济堂”的数据;

self.screeningButton.triggered.connect(self.dataScreening)
# 定向筛选
def dataScreening(self):
    if root:
        # 合并Excel表格
        filearray = []
        filelocation = glob.glob(root + "/*.xlsx")
        for filename in filelocation:
            filearray.append(filename)
        res = pd.read_excel(filearray[0], engine='openpyxl')
        for i in range(1, len(filearray)):
            a = pd.read_excel(filearray[i], engine='openpyxl')
            # 数据合并
            res = pd.concat([res, a], ignore_index=False, sort=True)
        # 显示指定列数据
        df = res[['code', 'name', 'trade', 'ticktime']]
        # 筛选数据
        df = df.loc[df['name'] == '同济堂']
        self.dataArea.setText(str(df))
        # 保存定向筛选结果到Excel
        saveExcel(df, self.rButton1.isChecked())

8. 实现点击“多表合并”按钮功能;函数setupUi添加“多表合并”点击触发,并添加触发函数代码,用来显示选择目录下所有文件合并后的数据;

self.mergeButton.triggered.connect(self.mergeData)
# 多表合并
def mergeData(self):
    if root:
        # 合并指定文件夹下的所有Excel表
        filearray = []
        filelocation = glob.glob(root + "/*.xlsx")
        for filename in filelocation:
            filearray.append(filename)
        res = pd.read_excel(filearray[0], engine='openpyxl')
        for i in range(1, len(filearray)):
            a = pd.read_excel(filearray[i], engine='openpyxl')
            res = pd.concat([res, a], ignore_index=False, sort=True)

        self.dataArea.setText(str(res))
        # 将合并后的数据保存到Excel
        saveExcel(res, self.rButton1.isChecked())

9. 实现点击“统计排行”按钮功能;函数setupUi添加“统计排行”点击触发,并添加触发函数代码,用来显示按列“trade”排行的数据;

self.rankingButton.triggered.connect(self.dataRanking)
# 多表统计排行
def dataRanking(self):
    if root:
        # 合并Excel表格
        filearray = []
        filelocation = glob.glob(root + "/*.xlsx")
        for filename in filelocation:
            filearray.append(filename)
        res = pd.read_excel(filearray[0], engine='openpyxl')
        for i in range(1, len(filearray)):
            a = pd.read_excel(filearray[i], engine='openpyxl')
            res = pd.concat([res, a], ignore_index=False, sort=True)
        # 分组统计排序
        # 通过reset_index()函数将groupby()的分组结果转成DataFrame对象
        df = res.groupby(["name"])["trade"].sum().reset_index()
        # 按'trade'倒序
        df = df.sort_values(by='trade', ascending=False)
        self.dataArea.setText(str(df))
        # 将统计排行结果保存到Excel
        saveExcel(df, self.rButton1.isChecked())

10. 实现点击“生成图表”按钮功能;函数setupUi添加“生成图表”点击触发,并添加触发函数代码,用来按列“code”-x和“trade”-y显示折线图;

Tips:使用的pyecharts是百度开源的数据可视化工具,有很多很炫的图表,有空可以试试。

self.reportButton.triggered.connect(self.dataReport)
# 生成图表
def dataReport(self):
    if root:
        # 合并Excel表格
        filearray = []
        filelocation = glob.glob(root + "/*.xlsx")
        for filename in filelocation:
            filearray.append(filename)
        res = pd.read_excel(filearray[0], engine='openpyxl')
        for i in range(1, len(filearray)):
            a = pd.read_excel(filearray[i], engine='openpyxl')
            res = pd.concat([res, a], ignore_index=False, sort=True)

        # 通过reset_index()函数将groupby()的分组结果转成DataFrame对象
        df = res.groupby(["code"])["trade"].sum().reset_index()

        # 绘制图标
        x_data = df['code']
        y_data = df['trade']
        (
            Line()
                .set_global_opts(
                tooltip_opts=opts.TooltipOpts(is_show=False),
                xaxis_opts=opts.AxisOpts(type_="category"),
                yaxis_opts=opts.AxisOpts(
                    type_="value",
                    axistick_opts=opts.AxisTickOpts(is_show=True),
                    splitline_opts=opts.SplitLineOpts(is_show=True),
                ),
            )
                .add_xaxis(xaxis_data=x_data)
                .add_yaxis(
                series_name="",
                y_axis=y_data,
                symbol="emptyCircle",
                is_symbol_show=True,
                label_opts=opts.LabelOpts(is_show=False),
            )
                .render("basic_line_chart.html")
        )

最终合并代码:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'dataAnalysis.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import qApp,QFileDialog

import sys
import pandas as pd
import os
import glob

import pyecharts.options as opts
from pyecharts.charts import Line

# 导入数据目录路径
root = ''
# 左边目录行数
rowIndex = 0
# 浏览选择的路径
tempRoot = ''

# 用于保存数据到Excel
def saveExcel(df, isChecked):
    # 将提取后的数据保存到Excel
    if (isChecked): # 保存在原文件夹内
        writer = pd.ExcelWriter('myExcel.xls', engine='openpyxl')
    else: # 自定义保存文件夹
        # 使用ExcelWriter()可以向同一个excel的不同sheet中写入对应的表格数据
        writer = pd.ExcelWriter(tempRoot + '/myExcel.xls', engine='openpyxl')
    df.to_excel(writer, 'sheet1')
    writer.save()

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(830, 601)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("images/icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.leftList = QtWidgets.QListView(self.centralwidget)
        self.leftList.setGeometry(QtCore.QRect(0, 0, 170, 400))
        self.leftList.setObjectName("leftList")
        self.dataArea = QtWidgets.QTextEdit(self.centralwidget)
        self.dataArea.setGeometry(QtCore.QRect(170, 0, 660, 400))
        self.dataArea.setObjectName("dataArea")
        self.filePath = QtWidgets.QTextEdit(self.centralwidget)
        self.filePath.setGeometry(QtCore.QRect(150, 472, 571, 30))
        self.filePath.setObjectName("filePath")
        self.operationTitle = QtWidgets.QLabel(self.centralwidget)
        self.operationTitle.setEnabled(True)
        self.operationTitle.setGeometry(QtCore.QRect(20, 412, 81, 21))
        font = QtGui.QFont()
        font.setPointSize(11)
        self.operationTitle.setFont(font)
        self.operationTitle.setObjectName("operationTitle")
        self.rButton1 = QtWidgets.QRadioButton(self.centralwidget)
        self.rButton1.setGeometry(QtCore.QRect(20, 446, 131, 16))
        self.rButton1.setChecked(True)
        self.rButton1.setObjectName("rButton1")
        self.rButton2 = QtWidgets.QRadioButton(self.centralwidget)
        self.rButton2.setGeometry(QtCore.QRect(20, 479, 121, 16))
        self.rButton2.setObjectName("rButton2")
        self.browseButton = QtWidgets.QPushButton(self.centralwidget)
        self.browseButton.setGeometry(QtCore.QRect(730, 472, 75, 30))
        self.browseButton.setObjectName("browseButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 830, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.toolBar = QtWidgets.QToolBar(MainWindow)
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.importButton = QtWidgets.QAction(MainWindow)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("images/import.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.importButton.setIcon(icon1)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.importButton.setFont(font)
        self.importButton.setObjectName("importButton")
        self.extractButton = QtWidgets.QAction(MainWindow)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("images/extract.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.extractButton.setIcon(icon2)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.extractButton.setFont(font)
        self.extractButton.setObjectName("extractButton")
        self.screeningButton = QtWidgets.QAction(MainWindow)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("images/screening.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.screeningButton.setIcon(icon3)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.screeningButton.setFont(font)
        self.screeningButton.setObjectName("screeningButton")
        self.mergeButton = QtWidgets.QAction(MainWindow)
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("images/merge.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.mergeButton.setIcon(icon4)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.mergeButton.setFont(font)
        self.mergeButton.setObjectName("mergeButton")
        self.rankingButton = QtWidgets.QAction(MainWindow)
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap("images/ranking.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.rankingButton.setIcon(icon5)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.rankingButton.setFont(font)
        self.rankingButton.setObjectName("rankingButton")
        self.reportButton = QtWidgets.QAction(MainWindow)
        icon6 = QtGui.QIcon()
        icon6.addPixmap(QtGui.QPixmap("images/report.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.reportButton.setIcon(icon6)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.reportButton.setFont(font)
        self.reportButton.setObjectName("reportButton")
        self.exitButton = QtWidgets.QAction(MainWindow)
        icon7 = QtGui.QIcon()
        icon7.addPixmap(QtGui.QPixmap("images/exit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.exitButton.setIcon(icon7)
        font = QtGui.QFont()
        font.setPointSize(8)
        self.exitButton.setFont(font)
        self.exitButton.setObjectName("exitButton")
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.importButton)
        self.toolBar.addAction(self.extractButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.screeningButton)
        self.toolBar.addAction(self.mergeButton)
        self.toolBar.addAction(self.rankingButton)
        self.toolBar.addAction(self.reportButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.exitButton)

        # 单击工具栏“退出”按钮退出程序
        self.exitButton.triggered.connect(qApp.quit)
        # 单击工具栏按钮触发自定义函数
        self.importButton.triggered.connect(self.showFile)
        self.extractButton.triggered.connect(self.extractData)
        self.screeningButton.triggered.connect(self.dataScreening)
        self.mergeButton.triggered.connect(self.mergeData)
        self.rankingButton.triggered.connect(self.dataRanking)
        self.reportButton.triggered.connect(self.dataReport)

        # 单击"浏览"按钮,选择文件存储路径
        self.browseButton.clicked.connect(self.browseButton_click)

        # 单击QListView列表触发自定义函数
        self.leftList.clicked.connect(self.showData)
        # 设置Dataframe对象显示所有列
        pd.set_option('display.max_columns', None)
        # 设置Dataframe对象列宽为200,默认为50
        pd.set_option('max_colwidth', 200)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "数据分析"))
        self.operationTitle.setText(_translate("MainWindow", "输出选项:"))
        self.rButton1.setText(_translate("MainWindow", "保存在原文件夹内"))
        self.rButton2.setText(_translate("MainWindow", "自定义保存文件夹"))
        self.browseButton.setText(_translate("MainWindow", "浏览"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
        self.importButton.setText(_translate("MainWindow", "导入数据"))
        self.importButton.setToolTip(_translate("MainWindow", "导入Excel"))
        self.extractButton.setText(_translate("MainWindow", "提取数据"))
        self.extractButton.setToolTip(_translate("MainWindow", "提取列数据"))
        self.screeningButton.setText(_translate("MainWindow", "定向筛选"))
        self.screeningButton.setToolTip(_translate("MainWindow", "定向筛选"))
        self.mergeButton.setText(_translate("MainWindow", "多表合并"))
        self.mergeButton.setToolTip(_translate("MainWindow", "多表合并"))
        self.rankingButton.setText(_translate("MainWindow", "统计排行"))
        self.rankingButton.setToolTip(_translate("MainWindow", "多表统计排行"))
        self.reportButton.setText(_translate("MainWindow", "生成图表"))
        self.reportButton.setToolTip(_translate("MainWindow", "生成图表"))
        self.exitButton.setText(_translate("MainWindow", "退出"))
        self.exitButton.setToolTip(_translate("MainWindow", "退出"))

    # 点击导入数据
    def showFile(self):
        # 文件夹路径
        global root
        root = QFileDialog.getExistingDirectory(None, "选择文件夹", os.getcwd())
        mylist = []
        # 遍历文件夹文件
        for dirpath, dirnames, filenames in os.walk(root):
            for filepath in filenames:
                mylist.append(os.path.join(filepath))
        # 实例化列表模型,添加数据列表
        self.model = QtCore.QStringListModel()
        # 添加列表数据
        self.model.setStringList(mylist)
        self.leftList.setModel(self.model)
        self.leftList = mylist

    # 单击左侧文件右侧显示数据
    def showData(self, qModelIndex):
        global rowIndex
        rowIndex = qModelIndex.row()
        # 获取当前选中行的数据
        a = root + '/' + str(self.leftList[rowIndex])
        print(root)
        df = pd.DataFrame(pd.read_excel(a, engine='openpyxl'))
        # 缺失数据填充(0)
        df = df.fillna(0)
        # 重复数据处理保留第一个
        df = df.drop_duplicates(subset='name')

        self.dataArea.setText(str(df))

    # 提取列数据
    def extractData(self):
        if root: # 导入数据才能处理
            # 获取当前选中行的数据
            a = root + '/' + str(self.leftList[rowIndex])
            df = pd.DataFrame(pd.read_excel(a, engine='openpyxl'))
            # 显示指定列数据
            df = df[['code', 'name', 'trade', 'ticktime']]
            self.dataArea.setText(str(df))
            # 保存数据到Excel
            saveExcel(df, self.rButton1.isChecked())

    # 定向筛选
    def dataScreening(self):
        if root:
            # 合并Excel表格
            filearray = []
            filelocation = glob.glob(root + "/*.xlsx")
            for filename in filelocation:
                filearray.append(filename)
            res = pd.read_excel(filearray[0], engine='openpyxl')
            for i in range(1, len(filearray)):
                a = pd.read_excel(filearray[i], engine='openpyxl')
                # 数据合并
                res = pd.concat([res, a], ignore_index=False, sort=True)
            # 显示指定列数据
            df = res[['code', 'name', 'trade', 'ticktime']]
            # 筛选数据
            df = df.loc[df['name'] == '同济堂']
            self.dataArea.setText(str(df))
            # 保存定向筛选结果到Excel
            saveExcel(df, self.rButton1.isChecked())

    # 多表合并
    def mergeData(self):
        if root:
            # 合并指定文件夹下的所有Excel表
            filearray = []
            filelocation = glob.glob(root + "/*.xlsx")
            for filename in filelocation:
                filearray.append(filename)
            res = pd.read_excel(filearray[0], engine='openpyxl')
            for i in range(1, len(filearray)):
                a = pd.read_excel(filearray[i], engine='openpyxl')
                res = pd.concat([res, a], ignore_index=False, sort=True)

            self.dataArea.setText(str(res))
            # 将合并后的数据保存到Excel
            saveExcel(res, self.rButton1.isChecked())

    # 多表统计排行
    def dataRanking(self):
        if root:
            # 合并Excel表格
            filearray = []
            filelocation = glob.glob(root + "/*.xlsx")
            for filename in filelocation:
                filearray.append(filename)
            res = pd.read_excel(filearray[0], engine='openpyxl')
            for i in range(1, len(filearray)):
                a = pd.read_excel(filearray[i], engine='openpyxl')
                res = pd.concat([res, a], ignore_index=False, sort=True)
            # 分组统计排序
            # 通过reset_index()函数将groupby()的分组结果转成DataFrame对象
            df = res.groupby(["name"])["trade"].sum().reset_index()
            # 按'trade'倒序
            df = df.sort_values(by='trade', ascending=False)
            self.dataArea.setText(str(df))
            # 将统计排行结果保存到Excel
            saveExcel(df, self.rButton1.isChecked())

    # 生成图表
    def dataReport(self):
        if root:
            # 合并Excel表格
            filearray = []
            filelocation = glob.glob(root + "/*.xlsx")
            for filename in filelocation:
                filearray.append(filename)
            res = pd.read_excel(filearray[0], engine='openpyxl')
            for i in range(1, len(filearray)):
                a = pd.read_excel(filearray[i], engine='openpyxl')
                res = pd.concat([res, a], ignore_index=False, sort=True)

            # 通过reset_index()函数将groupby()的分组结果转成DataFrame对象
            df = res.groupby(["code"])["trade"].sum().reset_index()

            # 绘制图标
            x_data = df['code']
            y_data = df['trade']
            (
                Line()
                    .set_global_opts(
                    tooltip_opts=opts.TooltipOpts(is_show=False),
                    xaxis_opts=opts.AxisOpts(type_="category"),
                    yaxis_opts=opts.AxisOpts(
                        type_="value",
                        axistick_opts=opts.AxisTickOpts(is_show=True),
                        splitline_opts=opts.SplitLineOpts(is_show=True),
                    ),
                )
                    .add_xaxis(xaxis_data=x_data)
                    .add_yaxis(
                    series_name="",
                    y_axis=y_data,
                    symbol="emptyCircle",
                    is_symbol_show=True,
                    label_opts=opts.LabelOpts(is_show=False),
                )
                    .render("basic_line_chart.html")
            )

    # 单击“浏览”按钮选择文件存储路径
    def browseButton_click(self):
        global tempRoot
        tempRoot = QFileDialog.getExistingDirectory(None, "选择文件夹", os.getcwd())
        self.filePath.setText(tempRoot)

# 主方法(添加代码)
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()  # 创建窗体对象
    ui = Ui_MainWindow()  # 创建PyQt设计的窗体对象
    ui.setupUi(MainWindow)  # 调用PyQt窗体的方法对窗体对象进行初始化设置
    MainWindow.show()  # 显示窗体
    sys.exit(app.exec_())  # 程序关闭时退出进程

最后结语

本文利用python+pandas,主要实现了对数据进行“缺失数据填充”、“去重”、“提取”、“筛选”、“合并”、“排行”、“生成图表”,并能保存本地或自定义保存路径;选取的文件数据用在这里不够典型,大家可使用月季度销售数据等比较典型的数据,且pandas还有其它功能可以使程序功能更完善。

 

                                                                             扫描公众号,了解更多实例分享

Guess you like

Origin blog.csdn.net/king0964/article/details/105997405