'Retrieving values based on other values (dataframe) - how to make my code more efficient?
So after much trying I've managed to get something a bit closer to what I intend to do.
Scenario is as follows, a dataframe with many columns of which one contains unique values. Lets say this column is called "Customer Name". This maps with a one to many match on a different column lets call that one "Customer Alias".
I need a dictionary that for each customer name as a key has as value a list containing every possible customer alias for that customer name.
mapping_customers = {x:list() for x in data['Customer Name']}
for each in mapping_customers.keys():
try:
selection_rows = data.loc[data['Customer Name'] == each]
mapping_customers[each].append(selection_rows['Customer Alias'])
except Exception as err:
print(err.args)
Right now the keys portion is working correctly but when appending the Customer Aliases they are not appended as individual items(strings) on a list. I basically get the Series in a list as the values in index position 0 and in index position 1, I see
'Series([], Name: Customer Alias, dtype: object)'
I would like to have each customer alias for a given customer name appear as an individual entry of that list.
Here is an example of what things would look like:
{'Great Customer': ['Great Customer LDA', 'Great Customer Enterprises','Great Customer Japan'],
'Best Customer': ['Best Offices', 'Best Customer LDA','BEST'],
}
Thanks in advance for your help!
Solution 1:[1]
IIUC, and building on @Leo's answer, would this work?
df = pd.DataFrame({'Customer Name': ['Great Customer','Great Customer','Great Customer','Best Customer','Best Customer','Best Customer'],
'Customer Alias': ['Great Customer LDA', 'Great Customer Enterprises', 'Great Customer Japan', 'Best Offices', 'Best Customer LDA', 'BEST']})
dfg = df.groupby('Customer Name').agg(list)
dict( zip( dfg.index, dfg["Customer Alias"]))
output
{'Best Customer': ['Best Offices', 'Best Customer LDA', 'BEST'],
'Great Customer': ['Great Customer LDA',
'Great Customer Enterprises',
'Great Customer Japan']}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jonathan Leon |
