티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to filter Pandas dataframe using 'in' and 'not in' like in SQL
SQL처럼 'in'과 'not in'을 사용하여 Pandas 데이터프레임을 필터링하는 방법
문제 내용
How can I achieve the equivalents of SQL's IN
and NOT IN
?
SQL의 IN 및 NOT IN과 동일한 결과를 얻으려면 어떻게 해야 하나요?
I have a list with the required values. Here's the scenario:
저는 필요한 값을 가진 리스트를 가지고 있습니다. 시나리오는 다음과 같습니다.
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
countries_to_keep = ['UK', 'China']
# pseudo-code:
df[df['country'] not in countries_to_keep]
My current way of doing this is as follows:
현재 이 작업을 수행하는 방법은 다음과 같습니다.
df = pd.DataFrame({'country': ['US', 'UK', 'Germany', 'China']})
df2 = pd.DataFrame({'country': ['UK', 'China'], 'matched': True})
# IN
df.merge(df2, how='inner', on='country')
# NOT IN
not_in = df.merge(df2, how='left', on='country')
not_in = not_in[pd.isnull(not_in['matched'])]
But this seems like a horrible kludge. Can anyone improve on it?
하지만 이것은 좋지 않습니다. 개선할 수 있는 사람이 있습니까?
높은 점수를 받은 Solution
You can use pd.Series.isin
.
pd.Series.isin을 사용할 수 있습니다.
For "IN" use: something.isin(somewhere)
"IN"의 경우: something.isin(somewhere)을 사용합니다.
Or for "NOT IN": ~something.isin(somewhere)
또는 "NOT IN"의 경우: ~something.isin(somewhere)
As a worked example:
실제 예로 다음을 들 수 있습니다.
>>> df
country
0 US
1 UK
2 Germany
3 China
>>> countries_to_keep
['UK', 'China']
>>> df.country.isin(countries_to_keep)
0 False
1 True
2 False
3 True
Name: country, dtype: bool
>>> df[df.country.isin(countries_to_keep)]
country
1 UK
3 China
>>> df[~df.country.isin(countries_to_keep)]
country
0 US
2 Germany
가장 최근 달린 Solution
You can also use .isin()
inside .query()
:
.query() 내부에서 .isin()을 사용할 수도 있습니다.
df.query('country.isin(@countries_to_keep).values')
# Or alternatively:
df.query('country.isin(["UK", "China"]).values')
To negate your query, use ~
:
쿼리를 부정하려면 ~를 사용하세요.
df.query('~country.isin(@countries_to_keep).values')
Update:
업데이트:
Another way is to use comparison operators:
또 다른 방법은 비교 연산자를 사용하는 것입니다.
df.query('country == @countries_to_keep')
# Or alternatively:
df.query('country == ["UK", "China"]')
And to negate the query, use !=
:
그리고 쿼리를 부정하려면 != 를 사용합니다.
df.query('country != @countries_to_keep')
출처 : https://stackoverflow.com/questions/19960077/how-to-filter-pandas-dataframe-using-in-and-not-in-like-in-sql
'개발 > 파이썬' 카테고리의 다른 글
파이썬에서 리스트에서 중복되지 않는 값만 가져오기 (0) | 2022.12.19 |
---|---|
데이터프레임 인덱스를 열로 변환하기 (0) | 2022.12.18 |
딕셔너리에 키가 없을 때도 에러 없이 기본 값 반환 받기 (0) | 2022.12.18 |
데이터프레임 행 순서 무작위로 섞기 (0) | 2022.12.17 |
특정 키만 포함하도록 딕셔너리를 필터링하기 (0) | 2022.12.17 |