如何在Python中使用Pandas读取多个excel文件

问题描述 投票:-1回答:1

我希望用户从他的计算机中选择两个文件,按下“计算”按钮后,程序将显示从这些Excel文件中读取的数据的串扰功能结果。我目前无法同时将两个Excel文件读入程序。这是我的代码

import numpy as np
import pandas as pd
from tkinter import filedialog as fd
from tkinter import ttk
from tkinter import *
import os.path as op

fileListA = ""
fileListB = ""
def SetFilePath1():
    #Getting the file from PC
    filepath = fd.askopenfilename(filetypes =(('Excel Files', '.xls'), ('Excel Files','*.xlsx')),parent=root)
    if isinstance(filepath, str):
        fileListA = filepath.split(" ")
    elif isinstance(filepath, tuple):
        fileListA = list(filepath)
    elif isinstance(filepath, list):
        fileListA = filepath
def SetFilePath2():
    #Getting the file from PC
    filepath = fd.askopenfilename(filetypes =(('Excel Files', '.xls'), ('Excel Files','*.xlsx')),parent=root)
    if isinstance(filepath, str):
        fileListB = filepath.split(" ")
    elif isinstance(filepath, tuple):
        fileListB = list(filepath)
    elif isinstance(filepath, list):
        fileListB = filepath
def GetFilePath1():
    #Getting the file from PC
    return fileListA
def GetFilePath2():
    #Getting the file from PC
    return fileListB
def Calculate():
    file1 = GetFilePath1()
    file2 = GetFilePath2()
    print("Inside Calculate")
    print(file1)

    print("Inside If Loop")

    if file1 == "":
        print("File 1 Not Found")
    elif file2 == "":
        print("File 2 Not Found")
    else:
        print("Inside If Loop")
        #Creating DataFrames as df1 & df2 with Header=None because currently no header in the excel files
        df1 = pd.read_excel(open(file1,'rb'), header=None)
        #Setting the header for the dataframes as title. This will not change anything in the original files
        df1.rename(columns={0 : 'title',},inplace=True)

        df2 = pd.read_excel(open(file2,'rb'), header=None)
        #Setting the header for the dataframes as title. This will not change anything in the original files
        df2.rename(columns={0 : 'title',},inplace=True)

        #Doing the mathematics line 24 to line 39
        df1['Value'] = (df1.title * 32.7) ** 2
        df2['Value'] = (df2.title * 32.7) ** 2

        df1['Emen'] = df1.Value * df2.Value

        #output is just one value of these sum and sqrt functions
        df1['TotalD'] = df1['Emen'].sum()
        df1['TotalC'] = df1['Value'].sum()
        df2['TotalC'] = df2['Value'].sum()

        df1['SqrtC'] = df1.TotalC ** 0.5
        df2['SqrtC'] = df2.TotalC ** 0.5

        df1['MulG'] = df1.SqrtC * df2.SqrtC
        df1['DivH'] = df1.TotalD / df1.MulG
        df1['SqH'] = df1.DivH * df1.DivH

        print("Here is the Cross-Talk: ")
        print(df1.SqH[0])


root = Tk()
root.title("Cross-Talk Calculator")     
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

ttk.Label(mainframe).grid(column=1, row=1, sticky=(W, E))
ttk.Button(mainframe, text="File 1", command=SetFilePath1).grid(column=1, row=1, sticky=E)

ttk.Label(mainframe).grid(column=2, row=1, sticky=(W, E))
ttk.Button(mainframe, text="File 2", command=SetFilePath2).grid(column=3, row=1, sticky=W)

ttk.Label(mainframe, text="The Cross Talk is: ").grid(column=1, row=5, sticky=E)
ttk.Label(mainframe).grid(column=3, row=3, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=lambda: Calculate()).grid(column=3, row=4, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

root.bind('<Return>')

root.mainloop()

代码的数学部分工作正常。我用print()知道我的代码当前在哪里。我在互联网上搜索了很多,但找不到任何问题的解决方案。提前致谢

python python-3.x pandas numpy tkinter
1个回答
0
投票

fileListAfileListB是全球变量。在函数SetFilePath1SetFilePath2中,您创建局部变量fileListAfileListB。您必须在函数中使用global来通知它们您要分配给全局变量。

顺便说一句:如果只从全局变量中获取值,则不必使用global - 就像在Calculate中一样。

fileListA = ""  # it is global variable (automatically)
fileListB = ""  # it is global variable (automatically)

def SetFilePath1():
    global fileListA # inform function to assign value (when you use `=`)   
                     # to external variable instead of creating local variable

    #Getting the file from PC
    filepath = fd.askopenfilename(filetypes =(('Excel Files', '.xls'), ('Excel Files','*.xlsx')),parent=root)
    if isinstance(filepath, str):
        fileListA = filepath.split(" ")
    elif isinstance(filepath, tuple):
        fileListA = list(filepath)
    elif isinstance(filepath, list):
        fileListA = filepath

def SetFilePath2():
    global fileListB # inform function to assign value (when you use `=`)   
                     # to external variable instead of creating local 

    #Getting the file from PC
    filepath = fd.askopenfilename(filetypes =(('Excel Files', '.xls'), ('Excel Files','*.xlsx')),parent=root)
    if isinstance(filepath, str):
        fileListB = filepath.split(" ")
    elif isinstance(filepath, tuple):
        fileListB = list(filepath)
    elif isinstance(filepath, list):
        fileListB = filepath

def Calculate():
    file1 = fileListA
    file2 = fileListB
    print("Inside Calculate")
    print(file1)
    # ... rest ...
© www.soinside.com 2019 - 2024. All rights reserved.