检索值基于其他值(dataframe) -如何使我的代码更有效?



所以经过多次尝试,我已经设法得到一些更接近我打算做的事情。

场景如下,一个数据框有许多列,其中一个列包含唯一的值。假设这一列名为"客户名称"。这与另一列上的一对多匹配相映射,我们将其称为"客户别名"。

我需要一个字典,对于每个客户名称作为键,其值为包含该客户名称的所有可能的客户别名的列表。

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)

现在键部分工作正常,但是当附加客户别名时,它们不是作为单独的项(字符串)附加到列表上。我基本上得到了一个列表中的Series作为索引位置0和索引位置1的值,我看到

'Series([], Name: Customer Alias, dtype: object)'

我希望给定客户名的每个客户别名显示为该列表的单个条目。

下面是一个示例:

{'Great Customer': ['Great Customer LDA', 'Great Customer Enterprises','Great Customer Japan'],
'Best Customer': ['Best Offices', 'Best Customer LDA','BEST'],
}

提前感谢您的帮助!

iuc,基于@Leo的回答,这可行吗?

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"]))

输出
{'Best Customer': ['Best Offices', 'Best Customer LDA', 'BEST'],
'Great Customer': ['Great Customer LDA',
'Great Customer Enterprises',
'Great Customer Japan']}

相关内容

最新更新