반응형
Pandas 데이터 프레임에서 문자열 패턴을 포함하는 행을 필터링하는 방법
이 질문에 이미 답변이 있습니다.
Python Pandas에 다음과 같은 데이터 프레임이 있다고 가정합니다.
df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': [u'aball', u'bball', u'cnut', u'fball']})
또는 표 형식 :
ids vals
aball 1
bball 2
cnut 3
fball 4
키워드 "ball"이 포함 된 행을 어떻게 필터링합니까? 예를 들어, 출력은 다음과 같아야합니다.
ids vals
aball 1
bball 2
fball 4
In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
ids vals
0 aball 1
1 bball 2
3 fball 4
df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1
단계별 설명 (내부에서 외부로) :
df['ids']
ids
데이터 프레임 의 열을 선택합니다 (기술적으로 객체df['ids']
는 유형pandas.Series
임).df['ids'].str
벡터화 된 문자열 메서드 (예 :lower
,contains
)를 Series 에 적용 할 수 있습니다.df['ids'].str.contains('ball')
요소 값에 문자열 'ball'이 하위 문자열로 포함되어 있는지 여부에 대해 Series의 각 요소를 확인합니다 . 결과는 부울의 시리즈 나타내는입니다True
또는False
는 '볼'문자열의 존재에 대해.df[df['ids'].str.contains('ball')]
데이터 프레임에 부울 '마스크'를 적용하고 적절한 레코드가 포함 된 뷰를 반환합니다.na = False
고려 사항에서 NA / NaN 값을 제거합니다. 그렇지 않으면 ValueError가 반환 될 수 있습니다.
>>> mask = df['ids'].str.contains('ball')
>>> mask
0 True
1 True
2 False
3 True
Name: ids, dtype: bool
>>> df[mask]
ids vals
0 aball 1
1 bball 2
3 fball 4
필터링 할 열을 새 색인으로 설정하려면
; 별도의 열로 유지
str.contains
하려면 갈 길입니다.당신이 가지고 있다고 가정합시다
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
계획은 새 색인으로 설정된 AND 를
ids
포함 하는 모든 행을 필터링하는 것입니다.
ball
ids
df.set_index('ids').filter(like='ball', axis=0)
주는
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.
반응형
'Programming' 카테고리의 다른 글
Perl에서 UTF-8을 어떻게 출력 할 수 있습니까? (0) | 2020.08.12 |
---|---|
주문이있는 Rails 4 has_many에 대한 비추천 경고 (0) | 2020.08.12 |
Windows 용 MSysGit 대 Git (0) | 2020.08.12 |
Asp.net WebApi의 사용자 지정 인증-엉망입니까? (0) | 2020.08.12 |
const 문자열 대 c #의 정적 읽기 전용 문자열 (0) | 2020.08.11 |