【问题标题】:Return unique difference between dict and dataframe records返回 dict 和 dataframe 记录之间的唯一差异
【发布时间】: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


    【解决方案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')]
    

    【讨论】:

    • @user3476463 yw :-) 快乐编码
    猜你喜欢
    • 2016-12-14
    • 2011-05-17
    • 1970-01-01
    • 2013-06-26
    • 2019-07-07
    • 2018-06-29
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多