Pandas: 문자열 길이를 기준으로 행을 필터링하는 방법
다음 방법을 사용하여 Pandas DataFrame에서 특정 길이의 문자열이 포함된 행을 필터링할 수 있습니다.
방법 1: 열의 문자열 길이를 기준으로 행 필터링
#filter rows where col1 has a string length of 5 df. loc [df[' col1 ']. str . len () == 5 ]
방법 2: 여러 열의 문자열 길이를 기준으로 행 필터링
#filter rows where col1 has string length of 5 and col2 has string length of 7 df. loc [(df[' col1 ']. str . len () == 5 ) & (df[' col2 ']. str . len () == 7 )]
다음 예에서는 다음 pandas DataFrame에서 실제로 각 메서드를 사용하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' conf ': ['East', 'East', 'North', 'West', 'North', 'South'], ' pos ': ['Guard', 'Guard', 'Forward', 'Center', 'Center', 'Forward'], ' points ': [5, 7, 7, 9, 12, 9]}) #view DataFrame print (df) conf pos points 0 East Guard 5 1 East Guard 7 2 North Forward 7 3 West Center 9 4 North Center 12 5 South Forward 9
예 1: 열의 문자열 길이를 기준으로 행 필터링
다음 코드는 conf 열에서 문자열 길이가 5 인 DataFrame의 행을 필터링하는 방법을 보여줍니다.
#filter rows where conf has a string length of 5 df. loc [df[' conf ']. str . len () == 5 ] conf pos points 2 North Forward 7 4 North Center 12 5 South Forward 9
conf 열의 문자열 길이가 5 인 행만 반환됩니다.
conf 열에서 두 개의 서로 다른 문자열이 이 기준을 충족하는 것을 볼 수 있습니다.
- “북쪽”
- “남쪽”
두 문자열의 길이는 모두 5 입니다.
예 2: 여러 열의 문자열 길이를 기준으로 행 필터링
다음 코드는 conf 열의 문자열 길이가 5 이고 pos 열의 문자열 길이가 7 인 DataFrame의 행을 필터링하는 방법을 보여줍니다.
#filter rows where conf has string length of 5 and pos has string length of 7 df. loc [(df[' conf ']. str . len () == 5 ) & (df[' pos ']. str . len () == 7 )] conf pos points 2 North Forward 7 5 South Forward 9
conf 열의 문자열 길이가 5 이고 pos 열의 강제 길이가 7 인 행만 반환됩니다.
참고 : 여기 에서 pandas의 str.len() 함수에 대한 전체 문서를 찾을 수 있습니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
조건에 따라 Pandas DataFrame에서 행을 삭제하는 방법
여러 조건에서 Pandas DataFrame을 필터링하는 방법
Pandas DataFrame에서 “NOT IN” 필터를 사용하는 방법