我的数据类似于下面的image_attr_df数据。我想将值的dict与数据帧中的指定记录列表进行比较,并返回一个dict,其中包含对原始dict唯一的列和值。
所以在这个例子中我将“purch”字典与image_id = [1615,1561]的记录进行比较。我想让我的代码返回:
{('Sleeve', 'Long sleeves')}
现在它返回的是每条记录不同的列和值。有没有人知道如何过滤最终的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')}
答案 0 :(得分:1)
我使用isin
def diff_attributes(df_na,dataset,To_compare):
compared=[]
for i in dataset.columns[1:]:
if ~dataset[i].isin(df_na.loc[df_na['image_id'].isin(To_compare),i]).any():
compared.append((i,dataset[i][0]))
return compared
input_df=df[['image_id','Neckline','Sleeve','Skin_exposure']]
comp_list=[1615,1561]
diff_attributes(input_df,purch,comp_list)
Out[142]: [('Sleeve', 'Longsleeves')]