【问题标题】:Search for value in dataframe that contains a list在包含列表的数据框中搜索值
【发布时间】:2015-11-16 11:31:28
【问题描述】:

我有一个如下所示的数据框:

id  points
a   [c,v,b,n]
b   []
c   [x,a]
....

和一个字典(我也有它作为数据框):

{'a': ['j','c'],
 'b': [p,r,q]
 'c': [n,k,l,x,a]
 ....}

我想搜索是否包含字典的键是数据帧的点,然后从字典点中删除字典中没有匹配的项目。预期输出:

id  points
a   [c]
b   []
c   [x,a]

我试过了

for key,point in my_dict.items():
    if df['points'].str.contains(point).any()

但我得到TypeError: unhashable type: 'list'

我尝试将数据框转换为字典,但搜索时间太长,因为我需要更多 for 循环。对代码或数据结构改进有何建议?

编辑

数据的另一种表示:

id  points
a   [c,v,b,n]
b   []
c   [x,a]
....

points
j,c
p,r,q
n,k,l,x,a

【问题讨论】:

    标签: python dictionary pandas dataframe


    【解决方案1】:

    您可以调用 apply 并将您的 dict 值转换为集合,可以将 intersection 转换为列表:

    In [15]:
    d={'a': ['j','c'],
     'b': ['p','r','q'],
     'c': ['n','k','l','x','a']}
    d
    
    Out[15]:
    {'a': ['j', 'c'], 'b': ['p', 'r', 'q'], 'c': ['n', 'k', 'l', 'x', 'a']}
    
    In [17]:
    df['points'] = df.apply(lambda row: list(set(d[row['id']]).intersection(row['points'])), axis=1)
    df
    
    Out[17]:
      id  points
    0  a     [c]
    1  b      []
    2  c  [a, x]
    

    至于为什么会出现错误,您试图在一个 dtype 列表的 Series 上调用 .str 方法,它们不是字符串。

    【讨论】:

    • 我遇到了一个关键错误。使用我添加到帖子中的两个数据框还有其他解决方案吗?
    • 您能否发布原始输入数据和所有代码以重现您的 dfs 以及您尝试过的引发错误的方法
    • 抱歉,因为我在发布之前仔细检查了我发现我的错误。这很有帮助!谢谢!
    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多