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 merged_df = pd.concat([merged_df, df])
Merge with the mapping file based on “Main account” column
merged_df = pd.merge(merged_df, mapping_df[["Main account", "Name y"]], left_on="MainAccount", right_on="Main account", how="left") #merged_df = pd.concat([merged_df, df])
merged_df = pd.concat([merged_df.reset_index(drop=True), df.reset_index(drop=True)], ignore_index=True)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")
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
print(merged_df.index) merged_df = merged_df.rename(columns={ "Projects": "Project ID", "Worker": "Worker ID", "Name y": "Name", "Description_4": "Project", "Position_y": "Position" })
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 reads multiple input files, a mapping file, and an employees details file. It then merges the input files based on certain columns and performs some data transformations. Finally, it writes the merged dataframe to an output Excel file.
Here is a breakdown of the code:
- Import the necessary libraries: pandas, tkinter, and os.
- Open a Tk window to allow the user to select input files using the
askopenfilenamesfunction fromtkinter.filedialog. - Prompt the user to select the mapping file and the employees details file using
askopenfilenames. - Read the mapping file and employees details file into pandas dataframes using the
pd.read_excelfunction. - Create an empty dataframe called
merged_dfto store the merged data. - Read and merge the input files using a loop. For each file, read it into a dataframe, perform some data transformations, and merge it with .
- User
Traceback (most recent call last): File "c:\Users\Dell\Desktop\Desktop Files\ERP\Merge Files Task\ProgramOutput.py", line 43, in merged_df = pd.merge(merged_df, employees_df[["Worker Name", "Position", "Description_4"]], on=["Worker Name"], how="left") ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Dell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\frame.py", line 3767, in getitem indexer = self.columns._get_indexer_strict(key, "columns")[1] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Dell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\indexes\base.py", line 5876, in _get_indexer_strict self._raise_if_missing(keyarr, indexer, axis_name) File "C:\Users\Dell\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pandas\core\indexes\base.py", line 5935, in _raise_if_missing raise KeyError(f"None of [{key}] are in the [{axis_name}]") KeyError: "None of [Index(['Worker Name', 'Position', 'Description_4'], dtype='object')] are in the [columns]"
- Assistant
It seems that there is an error with the column names in the employees details file. The error message suggests that the column names are not present in the dataframe.
Here are a few things you can check:
- Make sure that the column names in the employees details file exactly match the names specified in the code: "Worker Name", "Position", "Description_4". The column names are case-sensitive, so ensure they are spelled correctly.
- Verify that the employees details file has been correctly selected using the file dialog window. The file should have the ".xlsx" extension.
- Check that the employees details file contains data and is not empty.
By resolving these issues, you should be able to resolve the error.
- User
I need to avoid the duplicate formed because of multiple "Postion" for single "Worker Name"
- Assistant
To avoid duplicates in the merged dataframe caused by multiple "Position" values for a single "Worker Name", you can use the
drop_duplicatesfunction in pandas.After merging the
merged_dfdataframe with the employees details dataframe, you can add the following line of code:merged_df = merged_df.drop_duplicates(subset=["Worker Name"], keep="first")This line of code will remove all duplicate rows in
merged_dfbased on the "Worker Name" column and keep only the first occurrence of each unique "Worker Name". Adjust thesubsetparameter if you have additional columns that you want to consider when identifying duplicates.Here's the updated code:
# 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") # Remove duplicate rows based on “Worker Name” merged_df = merged_df.drop_duplicates(subset=["Worker Name"], keep="first")By doing this, you should be able to avoid duplicates in the merged dataframe caused by multiple "Position" values for a single "Worker Name".
- User
above code will not be correct since we have same and need multiple Worker Name but we need to concatenate and list only one time position and not duplicate records based on postion
- Assistant
Apologies for the confusion. If you want to concatenate and list the positions for each worker name without duplicating records, you can modify the code as follows:
# 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") # Concatenate and list the positions for each worker name merged_df["Position"] = merged_df.groupby("Worker Name")["Position"].transform(lambda x: ", ".join(x.dropna().unique())) # Remove duplicate rows based on all columns merged_df = merged_df.drop_duplicates()In this updated code snippet, the positions for each worker name are concatenated into a single string separated by commas and assigned to the "Position" column. The
groupbyfunction is used to group the dataframe by "Worker Name" and then thetransformfunction is applied to concatenate and list the unique positions for each group. Finally, the duplicated rows in the merged dataframe are removed using thedrop_duplicatesfunction without specifying any subset, which by default considers all columns for comparison.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.