首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >返回dict和dataframe记录之间的唯一差异

返回dict和dataframe记录之间的唯一差异
EN

Stack Overflow用户
提问于 2018-06-11 08:58:04
回答 1查看 19关注 0票数 0

我有类似下面的image_attr_df数据的数据。我想将一个值的dict与来自dataframe的指定记录列表进行比较,并返回一个具有原始dict所特有的列和值的dict。

因此,在本例中,我将"purch“字典与image_id = 1615,1561的记录进行比较。我想让我的代码返回:

代码语言:javascript
复制
{('Sleeve', 'Long sleeves')}

现在,它返回每条记录不同的列和值。有谁知道我如何过滤最终的字典,只返回一个只包含唯一列和值的字典(就像我上面的例子一样)?

img_attr_df

代码语言:javascript
复制
   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

代码语言:javascript
复制
   image_id Neckline        Sleeve Skin_exposure
0       619  V-shape  Long sleeves  Low exposure

代码:

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
[{('Sleeve', 'Long sleeves')},
 {('Neckline', 'V-shape'), ('Sleeve', 'Long sleeves')}]

所需输出:

代码语言:javascript
复制
{('Sleeve', 'Long sleeves')}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-11 09:13:38

我使用isin略微更改了您的函数

代码语言:javascript
复制
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')]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50789339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档