Pandas : 사전에 특정 값이 포함 된 행 선택

Nov 13 2020

하나의 열에 모든 행에 대한 사전이 포함 된 데이터 프레임이 있습니다. 사전에 특정 값이 포함 된 행을 선택하고 싶습니다. 어떤 키가 포함되어 있는지는 중요하지 않습니다.

사전에는 많은 수준이 있습니다 (많은 목록, 많은 사전, 다시 많은 목록 등 포함). 데이터는 다음과 유사하게 보일 수 있지만 사전은 더 복잡합니다.

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())

내가 아는 행에도 'specific_value'가 포함되어 있어도 "false"가됩니다. 레이어 때문인지 확실하지 않습니다.

답변

1 DaniMesejo Nov 13 2020 at 22:30

재귀 함수를 사용하여 특정 값 을 검색 할 수 있습니다 .

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입니다.