Skip to content

Instantly share code, notes, and snippets.

@darkmanlv
Created May 22, 2024 20:31
Show Gist options
  • Save darkmanlv/704fec4f1fefa92dd857b5813384b603 to your computer and use it in GitHub Desktop.
Save darkmanlv/704fec4f1fefa92dd857b5813384b603 to your computer and use it in GitHub Desktop.
update one csv file with data from other csv file
import pandas as pd
# Read the first CSV file with semicolon separator
file1 = 'file1.csv'
df1 = pd.read_csv(file1, sep=';', skiprows=1)
# Read the second CSV file with semicolon separator
file2 = 'file2.csv'
df2 = pd.read_csv(file2, sep=';', skiprows=1)
# Merge the two dataframes based on column 4 of file1 and column 1 of file2
merged_df = pd.merge(df1, df2, left_on=df1.columns[3], right_on=df2.columns[0], how='left', suffixes=('', '_from_file2'))
# Update column 21 of the first dataframe with column 2 of the second dataframe
df1[df1.columns[20]] = merged_df[df2.columns[1]]
# Update column 22 of the first dataframe with column 3 of the second dataframe
df1[df1.columns[21]] = merged_df[df2.columns[2]]
# Save the updated dataframe back to a CSV file with semicolon separator
df1.to_csv('updated_file1.csv', sep=';', index=False)
print("File updated successfully!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment