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

如何在Python中使用Pandas读取多个excel文件,python,python-3.x,pandas,numpy,tkinter,Python,Python 3.x,Pandas,Numpy,Tkinter,我希望用户从计算机中选择两个文件,按下“计算”按钮后,程序将显示从这些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 = "" fileLis

我希望用户从计算机中选择两个文件,按下“计算”按钮后,程序将显示从这些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知道我的代码目前在哪里。我在网上搜索了很多,但找不到任何解决问题的方法。 提前感谢

fileListA和fileListB是全局变量。在函数SetFilePath1和SetFilePath2中,创建局部变量fileListA和fileListB。您必须使用全局in函数来通知它们您要分配给全局变量

顺便说一句:如果您只从全局变量(如Calculate中)获取值,则不必使用全局变量


请说明我目前无法将两个Excel文件同时读入程序的原因。这是我的密码。错误消息?意外行为?您在函数中创建了局部变量fileListA和fileListB。在函数中,您必须使用全局文件列表A和/或全局文件列表B来通知函数如何使用外部全局变量。顺便说一下:-我们更愿意使用大写的类名称,如Label、Button,以及小写的函数/变量/实例名称,如set_file_path2,以使代码更具可读性。即使如此,SO也知道这个建议,并为类使用浅蓝色。如果可以直接获取fileListA,那么使用GetFilePath1是没有意义的-file1=fileListA。Python不是Java,它不喜欢getter/setter方法getSomething,setSomething当我们谈到样式指南时,它通过在函数之间添加一到两个换行来提高可读性,就像furas的回答一样。代码给出了一个错误名称error:name'FileListA'未定义@furasin示例中,我没有将'FileListA'与上F一起使用-很可能您的代码中有带上F的'FileListA'。完整的错误消息回溯应该显示您在哪一行出错。
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 ...