将列值匹配到dict [英] Match column values to dict

查看:65
本文介绍了将列值匹配到dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典和一个数据框,如下面的示例v和df.我想搜索df中的项目,并返回具有与dict中的值相同的最大字段值数量的项目.在这种情况下,它应该是项目3.我只是无法安静地直奔它.如果任何人有一个巧妙的方法来执行此操作或任何提示,将不胜感激.

I have a dict and a dataframe like the examples v and df below. I want to search through the items in df and return the item that has the maximum number of field values in common with the values in the dict. In this case it would be item 3. I was thinking maybe using apply with a lambda function, or transposing the df. I just can't quiet get my head around it. If anyone has a slick way to do this or any tips they're greatly appreciated.

输入:

v={'size':1,'color':red}

df:

item size color
2    2    red
3    1    red

Output:
3

推荐答案

另一种解决方案是使用字典而不是数据框:

An alternative solution is to work with dictionaries instead of dataframes:

v = {'size': 1, 'color': 'red'}

match_count = {}

fields = df.columns[1:]

for k, value in df.to_dict(orient='index').items():
    match_count[value['item']] = sum(value[i] == v[i] for i in fields & v.keys())

结果

print(match_count)
# {2: 1, 3: 2}

res = max(match_count.items(), key=lambda x: x[1])

print(res)
# (3, 2)

这篇关于将列值匹配到dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆