I want to optimize a process of a "vlookup" in Python that works but is not scalable in its current form. I have tried pythons pivot.table and pivot but it's been limited due to alphanumeric and string values in cells. I have two tables:
table1:
| ProductID | Sales |
|---|---|
| 123456 | 34 |
| abc123 | 34 |
| 123def | 34 |
| a1234f | 34 |
| 1abcd6 | 34 |
table2:
| Brand | Site1 | Site2 | Site3 |
|---|---|---|---|
| Brand1 | 123456 | N/A | N/A |
| Brand2 | N/A | abc123 | N/A |
| Brand1 | N/A | N/A | 123def |
| Brand2 | N/A | 1abcd6 | N/A |
| Brand1 | a1234f | N/A | N/A |
What I originally wanted to see was sales by brand:
| Brand | Sales |
|---|---|
| Brand1 | 102 |
| Brand2 | 68 |
Here's the pseudocode I've basically built out in Python and Pandas:
# read sales and product tables into pandas
sales_df = pd.read_csv(table1)
product_df = pd.read_csv(table2)
# isolate each product id column into separate dfs
product_site1_df = product_df.drop(['Site2', 'Site3'],axis=1)
product_site2_df = product_df.drop(['Site1', 'Site3'],axis=1)
product_site3_df = product_df.drop(['Site1', 'Site2'],axis=1)
# rename and append all product ids into a single column
product_site1_df.rename(columns={"Site1": "ProductID"})
product_site2_df.rename(columns={"Site2": "ProductID"})
product_site3_df.rename(columns={"Site3": "ProductID"})
product_list_master_df = pd.concat([product_site1_df, product_site2_df, product_site3_df])
#compare sales df and product df, pulling brand in as a new column to the sales table
inner_join = pd.merge(sales_df,
product_df,
on ='ProductID',
how ='inner')
This is obviously very procedural, not scalable, computationally redundant, and seems very round-about to get to what I want. Additionally, I'm losing data such as if I want to do a pivot based on sites rather than sales. Short of changing the data model itself, what can I do here to improve speed, versatility, and lines of code?