본문 바로가기
Computer Science & AI/데이터 전처리

Pandas > 데이터 Query 방법

by 오케미 2021. 8. 25.

Pandas > 데이터 Query 방법 (사용빈도 상)

특정 데이터 추출에 정말 많이 사용되는 함수.

비교연산, 논리연산, in 연산, 외부 변수(함수) 참조연산, 인덱스 검색, 문자열 부분검색 가능

쿼리한 결과를 데이터 프레임으로 받거나 해당 데이터 프레임을 덮어 쓰는 식으로 사용

 

* 컬럼명에 공백이 포함될 경우(backtick, ` ) 으로 감싸 사용해야 함(예제 5번 참조)


Base

DataFrame.query(expr, inplace=False, **kwargs)

Parameters

이름 자료형 설명
expr String 평가할 쿼리 문자열, 예제에서 추가로 다룸
inplace Bool 기본값 False.
True로 설정 시 대상 데이터프레임의 쿼리의 결과로 해당 데이터프레임을 덮어 씀

Returns

DataFrame or None(inplace=True 일 경우에)


예제

샘플 Code & Result

# sample code
import pandas as pd

animal = [["rabbit", 30, "Warrior - Hero"], 
	["frog", 5, "Theif - Assassin"], 
	["bee", 4, "Warrior - Hero"]]

df = pd.DataFrame(animal, columns=["Name","Age","Class"])
print(df)

# result - print(df)
"""
     Name  Age             Class
0  rabbit   30    Warrior - Hero
1    frog    5  Theif - Assassin
2     bee    4    Warrior - Hero
"""

 

 


예제 1. 비교 연산자( >, >=, ==, <=, <, != )

# EX 1 : 
df_ex1 = df.query("Age >= 5")
print(df_ex1)

# result - print(df_ex1)
"""
     Name  Age            Maple Class
0  rabbit   30  Warrior - Dark Knight
1    frog    5       Theif - Assassin
"""

예제 2. in 연산자( in, not in )

# EX 2 :
df_ex2 = df.query("Age not in [5, 30]")
print(df_ex2)

# result - print(df_ex2)
"""
  Name  Age     Maple Class
2  bee    4  Warrior - Hero
"""

예제 3. 논리 연산자( and, or, not )

# EX 3 : 논리 연산자 ( and, or, not )
df_ex3 = df.query("(Age >= 5) and (Name == 'rabbit')")
print(df_ex3)

# result - print(df_ex3)
"""
     Name  Age            Maple Class
0  rabbit   30  Warrior - Dark Knight
"""

예제 4. index 검색

# EX 4 : index 검색
df_ex4 = df.query("index == 1")
print(df_ex4)

# result - print(df_ex4)
"""
   Name  Age       Maple Class
1  frog    5  Theif - Assassin
"""

예제 5. 문자열 부분 검색 ( str.contains, str.startswith, str.endswith )

# EX 5 : 문자열 부분 검색 ( str.contains, str.startswith, str.endswith )
user_name = 'frog'
df_ex5 = df.query("(Age >= 5) and (Name == @user_name) or (`Maple Class`.str.contains('Knight'))")
print(df_ex5)

# result - print(df_ex5)
"""
     Name  Age            Maple Class
0  rabbit   30  Warrior - Dark Knight
1    frog    5       Theif - Assassin
"""


Reference

  • https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.query.html
  • https://m.blog.naver.com/wideeyed/221867273249

 

댓글