import pandas as pd from tkinter import Tk from tkinter.filedialog import…
- User
import pandas as pd from tkinter import Tk from tkinter.filedialog import askopenfilenames import os
Open a Tk window
Tk().withdraw()
Prompt the user to select input files
input_files = askopenfilenames(title="Select input files", filetypes=[("Excel Files", "*.xlsx")])
Prompt the user to select the “Staff Gl Mapping.xlsx” file
mapping_file = askopenfilenames(title="Select Staff Gl Mapping file", filetypes=[("Excel Files", ".xlsx")])
Prompt the user to select the “Employees Details Report old.xlsx” file
employees_file = askopenfilenames(title="Select Employees Details Report file", filetypes=[("Excel Files", ".xlsx")])
Read the mapping file
mapping_df = pd.read_excel(mapping_file[0])
Read the employees details file
employees_df = pd.read_excel(employees_file[0])
Create an empty dataframe to store merged data
merged_df = pd.DataFrame()
Read and merge the input files
for file in input_files: df = pd.read_excel(file) df["Project Description"] = df["Name"].str.split("|").str[2] df["Worker Name"] = df["Name"].str.split("|").str[4] df["Current"] = df["Debit"] - df["Credit"] df = df.rename(columns={"Closing balance": "Cumulative"}) file_name, _ = os.path.splitext(os.path.basename(file)) df["Date"] = file_name
print(mapping_df.columns)
Merge with the mapping file based on “Main account” column
df = pd.merge(df, mapping_df[["Main account", "Name y"]], left_on="MainAccount", right_on="Main account", how="left") merged_df = pd.concat([merged_df, df])
Merge with the employees details file based on “Worker Name” and “Personal Number” columns
merged_df = pd.merge(merged_df, employees_df[["Worker Name", "Position", "Description_4"]], on=["Worker Name"], how="left") #merged_df = merged_df.drop_duplicates(subset=["Worker Name"])
Remove the unwanted columns
unwanted_cols = ["MainAccount", "Division", "Site", "Name", "Opening balance","Main account"] merged_df = merged_df.drop(columns=unwanted_cols)
Rename the columns
merged_df = merged_df.rename(columns={ "Projects": "Project ID", "Worker": "Worker ID", "Name y": "Name", "Description_4": "Project", "Position_y": "Position" })
print(merged_df.columns)
Reorder the columns
new_order = ["Project ID", "Project Description", "Date", "Worker ID", "Worker Name", "Name", "Current", "Cumulative", "Position", "Project"] merged_df = merged_df[new_order]
Write the merged dataframe to an output Excel file
output_file = "merged_data.xlsx" merged_df.to_excel(output_file, index=False)
print("Merged dataframe has been written to", output_file)
- Assistant
The code provided prompts the user to select input files, a "Staff Gl Mapping.xlsx" file, and an "Employees Details Report old.xlsx" file. It then reads the mapping file and employees details file into pandas dataframes.
Next, the code creates an empty dataframe to store merged data. It reads and merges the input files, splitting the "Name" column and renaming certain columns. It then merges the dataframe with the mapping file based on the "Main account" column and with the employees details file based on the "Worker Name" column. Unwanted columns are dropped, and column names are renamed. The columns are reordered and the merged dataframe is written to an output Excel file.
Please note that the code provided is incomplete and contains some commented-out code.
- User
Index(['Level 1', 'Level 2', 'Level 3', 'Level 4', 'Main account', 'Name', 'Main account type', 'Main account category', 'Name y'], dtype='object') Index(['Project ID', 'Worker ID', 'Debit', 'Credit', 'Cumulative', 'Project Description', 'Worker Name', 'Current', 'Date', 'Name', 'Position', 'Project'], dtype='object') Merged dataframe has been written to merged_data.xlsx Traceback (most recent call last): File "c:\Users\Dell\Desktop\Desktop Files\ERP\Merge Files Task\mergefiles_interactive.py", line 78, in merged_df = merged_df.drop(columns=unwanted_cols) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Dell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\frame.py", line 5258, in drop return super().drop( ^^^^^^^^^^^^^ File "C:\Users\Dell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\generic.py", line 4549, in drop obj = obj._drop_axis(labels, axis, level=level, errors=errors) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Dell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\generic.py", line 4591, in _drop_axis new_axis = axis.drop(labels, errors=errors) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Dell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\indexes\base.py", line 6696, in drop raise KeyError(f"{list(labels[mask])} not found in axis") KeyError: "['Main account'] not found in axis"
- Assistant
The error occurs because the column "Main account" does not exist in the merged dataframe when trying to drop it. This could be due to the renaming of columns earlier in the code.
To fix the issue, you can update the "unwanted_cols" list to contain the renamed column "Name y" instead of "Main account". Replace the line:
unwanted_cols = ["MainAccount", "Division", "Site", "Name", "Opening balance", "Main account"]with:
unwanted_cols = ["MainAccount", "Division", "Site", "Name", "Opening balance", "Name y"]This will ensure that the correct column is dropped from the merged dataframe.
- User
- Assistant
The error occurs because the code is attempting to concatenate the dataframes without resetting the index of each dataframe. This can result in duplicate index values, causing the error.
To fix the issue, you can reset the index of each dataframe before concatenating them. Replace the line:
merged_df = pd.concat([merged_df, df])with:
merged_df = pd.concat([merged_df.reset_index(drop=True), df.reset_index(drop=True)], ignore_index=True)This will reset the index of each dataframe and ensure that the index is unique when concatenating them.
Additionally, there is an issue with the reordering of columns. The line:
merged_df = merged_df[new_order]should be placed after the merging and column renaming process. Move this line after the line:
merged_df = merged_df.rename(columns=...)This will ensure that the column order is applied correctly to the merged dataframe.
- User
how to avoid the code looping multiple times
- Assistant