-
[pandas] 검사할 키워드 여러 개 , list + any데이터분석 2023. 3. 21. 11:09
any() : 하나라도 True인게 있으면 True 반환
all() : 모두 True 여야 True 반환
lines_list = ['apple is red', 'banana is yellow', 'cherry is red', 'durian is spiky'] # "red", "banana", or "cherry" 등 제외하고 싶은 리스트로 만들고 exclude_words = ["red", "banana", "cherry"] # lines_list 의 원소인 line에 exclude_words의 원소인 word가 있는지 검사하고 # 하나라도 걸리면 제외시키도록 filtered_lines = [line for line in lines_list if not any(word in line for word in exclude_words)] # 결과 print(filtered_lines) # Output: ['durian is spiky']
pandas dataframe에서도 유사하게 사용
import pandas as pd df = pd.DataFrame({ 'fruit': ['apple', 'banana', 'cherry', 'durian'], 'color': ['red', 'yellow', 'red', 'green'], 'texture': ['smooth', 'smooth', 'rough', 'spiky'] }) # red, yellow가 들어가면 제외 exclude_words = ["red", "yellow"] # not, isin ,any filtered_df = df[~df.isin(exclude_words).any(axis=1)] print(filtered_df)
'데이터분석' 카테고리의 다른 글
특정 연도 이전,이후 인덱스 찾는 방법 (0) 2023.03.14 [pandas] 아이디 기준으로 최근 거래 항목 3개 뽑고 싶을 때 groupby ,tail (0) 2022.11.25 [pandas], 콤마 제외하고 특수 문자 제거 ( 데이터프레임, replace, 정규표현식) (0) 2022.11.11 [pandas]데이터프레임 행 단위 연산 (apply, 조건에 맞게 처리,예외 처리) (0) 2022.11.10 [pandas] read_csv 화폐 단위 열 콤마(,) 제외하고 숫자로 읽어오기 (0) 2022.10.14