【问题标题】:Pandas: Select rows whose dictionary contains a specific valuePandas:选择字典包含特定值的行
【发布时间】:2021-09-19 23:29:44
【问题描述】:

我有一个数据框,其中一列包含每一行的字典。我想选择其字典包含特定值的行。不管哪个键包含它。

字典有很多级别(它们包含很多列表,有很多字典,还有很多列表等等)。 数据可能与此类似,但字典更复杂:

df = pd.DataFrame({"A": [1,2,3], "B": [{"a":1}, {"b":**specific_value**}, {"c":3}]})
   A         B
0  1  {'a': 1}
1  2  {'b': 2}
2  3  {'c': 3}

我试过了:

df.B.apply(lambda x : 'specific_value' in x.values())

即使我知道的行包含“特定值”,我也会得到“错误”。我不确定是不是因为层。

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    您可以使用递归函数来搜索特定值

    import pandas as pd
    
    
    def nested_find_value(d, needle=4):
        # we assume d is always a list or dictionary
        haystack = d.values() if isinstance(d, dict) else d
        
        for hay in haystack:
            if isinstance(hay, (list, dict)):
                yield from nested_find_value(hay, needle)
            else:
                yield hay == needle
    
    
    def find(d, needle=4):
        return any(nested_find_value(d, needle))
    
    
    df = pd.DataFrame({"A": [1, 2, 3], "B": [{"a": 1}, {"b": {"d": 4}}, {"c": 3}]})
    
    result = df["B"].apply(find)
    print(result)
    

    输出

    0    False
    1     True
    2    False
    Name: B, dtype: bool
    

    在上面的示例中,特定值4

    【讨论】:

    • 感谢您的回答。不过,您编写的代码似乎不适用于我的 python 版本。我得到“TypeError:isinstance() arg 2 must be a type or tuple of types”。我认为这与此有关,但我不明白他们提供的答案:stackoverflow.com/questions/14681096/…
    • @EmilJessen 您的任何变量是否命名为 dict 或 list?
    • 没有。但是,我确实意识到使用“if isinstance(hay, (builtins.list, builtins.dict)):” 有效。
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2016-05-28
    • 2021-12-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    相关资源
    最近更新 更多