遍历文件并通过一个函数传递每个文件

时间:2019-10-13 15:46:41

标签: python pandas tabula

我正在尝试构建预算计算器以练习python。目前,我正在尝试遍历目录中的文件,然后将每个文件通过一个函数传递,以将所需的数据提取到DataFrame中(准备对其执行计算)。

我设法创建了清理数据的函数,并创建了一个for循环来遍历文件。但是,我无法弄清楚如何为每次迭代附加DataFrame。

#Where to look
os.chdir(r"C:\relevant\directory")
cwd = os.getcwd()

#key variables
main_df = pd.DataFrame()
pay_slip = {}
master_df = pd.DataFrame()

#Iterate over files
for file in os.listdir():
    slip_content = read_pdf(file)
    pay_slip[file] = slip_content

#Data clean up function
def get_key_info(pay_slip):
    read_dictionary = pay_slip.get(file)
    salary_str = read_dictionary["Employee"].iloc[2]
    pay_after_tax_str = read_dictionary["Tax Period"].iloc[14]
    date_format = read_dictionary["Pay Date"].iloc[0]
    salary = int(float(salary_str[1:].replace(",", "")))
    pay = int(float(pay_after_tax_str[1:].replace(",", "")))
    deductions = (salary - pay)
    df = pd.DataFrame([
        [date_format, salary, pay, deductions]
        ],
        columns=["Payment date", "Salary before tax", "take home pay", "total deductions"])
    return df

print(get_key_info(pay_slip))

运行此代码时,只有一个文件被添加到DataFrame中,而不是应有的所有文件。

在此先感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您不会遍历pay_slip字典。


for file in os.listdir(): 
    slip_content = read_pdf(file) 
    pay_slip[file] = slip_content 

#Data clean up function
def get_key_info(pay_slip): 
    read_dictionary = pay_slip.get(file) #<= where is file variable assign?

答案 1 :(得分:0)

感谢弗洛里安(Florian)的帮助,我已按照您所说的解决了在目录中循环播放的问题。

但是,我无法遍历字典,因为它不可哈希。

我将在下面发布我的代码,以防其他人遇到与我相同的问题。

    #Where to look
os.chdir(r"C:\relevant\directory")
cwd = os.getcwd()

#key variables
master_df = pd.DataFrame()


#Data clean up function
def get_key_info(x):
    salary_str = get_data["Employee"].iloc[2]
    pay_after_tax_str = get_data["Tax Period"].iloc[14]
    date_format = get_data["Pay Date"].iloc[0]
    salary = int(float(salary_str[1:].replace(",", "")))
    pay = int(float(pay_after_tax_str[1:].replace(",", "")))
    deductions = (salary - pay)
    df = pd.DataFrame([
        [date_format, salary, pay, deductions]
        ],
        columns=["Payment date", "Salary before tax", "take home pay", "total deductions"])
    return df

#Iterate over files
for f in os.listdir():
    get_data = read_pdf(f)
    master_df = master_df.append(get_key_info(f), ignore_index = True)

print(master_df)

在这里,我设置了变量get_data来更改for循环的每次迭代,然后它将.append() the master_df