I have two CSV files, table1 and table2, and I am trying to find a way to update the Price field in table1 with price values from table2 if-and-only-if table1 and table2 share the same value in the Name field.
My two tables look like this:
Table 1:
Price Name ATT1 ATT2
0 12 APPL 69 81
1 900 GOOGL 303 392
2 32 INV 39 9
Table 2:
Price Name
0 1231 APPL
1 39 FACEBOOK
Successfully performing this join/merge/update would see:
- APPL's price changed to
1231(from table2) - GOOGL and INV unchanged (no matching names from table2)
- FACEBOOK left out (no matching name from table1)
Expected Final Table:
Name ATT1 ATT2 Price
0 APPL 69 81 1231.0
1 GOOGL 303 392 900
2 INV 39 9 32
Current code:
table1 = pd.read_csv('path/table1.csv', index_col=0)
table2 = pd.read_csv('path/table2.csv', index_col=0)
print(table1)
print(table2)
new_table = table1[["Name ", "ATT1", "ATT2"]].merge(table2[["Price", "Name "]], on="Name ", how="left")
print(new_table)
leads to the following, GOOGL and INV being nullified:
Current Final Table:
Name ATT1 ATT2 Price
0 APPL 69 81 1231.0
1 GOOGL 303 392 NaN
2 INV 39 9 NaN