【发布时间】:2018-11-20 05:00:37
【问题描述】:
我有像下面的 image_attr_df 数据这样的数据。我想将值的字典与数据帧中指定的记录列表进行比较,并返回一个字典,其列和值对于原始字典是唯一的。
所以在这个例子中,我将“purch”字典与 image_id = [1615, 1561] 的记录进行比较。我想让我的代码返回:
{('Sleeve', 'Long sleeves')}
现在它正在返回每条记录不同的列和值。有谁知道我如何过滤最终的 dict 以仅返回具有唯一列和值的 dict(如我上面的示例?)
img_attr_df:
image_id Neckline Sleeve Skin_exposure
0 619 V-shape Long sleeves Low exposure
1 1615 V-shape Short sleeves Low exposure
2 1561 Round Short sleeves Low exposure
purch:
image_id Neckline Sleeve Skin_exposure
0 619 V-shape Long sleeves Low exposure
代码:
def diff_attributes(df_na,dataset,To_compare):
compared=[]
for i in To_compare:
compared.append(set(dataset.loc[:,input_df.columns!='image_id'].to_dict(orient ='records')[0].items())-set(df_na[df_na['image_id']==i].loc[:,input_df.columns!='image_id'].to_dict(orient ='records')[0].items()))
return compared
input_df=img_attr_df[['image_id','Neckline','Sleeve','Skin_exposure']]
comp_list=[1615,1561]
diff_attributes(input_df,purch,comp_list)
输出:
[{('Sleeve', 'Long sleeves')},
{('Neckline', 'V-shape'), ('Sleeve', 'Long sleeves')}]
期望的输出:
{('Sleeve', 'Long sleeves')}
【问题讨论】:
标签: python-3.x pandas