정규식으로 팬더의 행을 필터링하는 방법
열 중 하나에서 정규 표현식을 사용하여 데이터 프레임을 깨끗하게 필터링하고 싶습니다.
고안된 예 :
In [210]: foo = pd.DataFrame({'a' : [1,2,3,4], 'b' : ['hi', 'foo', 'fat', 'cat']})
In [211]: foo
Out[211]:
a b
0 1 hi
1 2 foo
2 3 fat
3 4 cat
f
정규식 을 사용하여 시작하는 행을 필터링하고 싶습니다 . 먼저 가십시오 :
In [213]: foo.b.str.match('f.*')
Out[213]:
0 []
1 ()
2 ()
3 []
그다지 유용하지 않습니다. 그러나 이것은 내 부울 인덱스를 얻습니다.
In [226]: foo.b.str.match('(f.*)').str.len() > 0
Out[226]:
0 False
1 True
2 True
3 False
Name: b
그래서 나는 다음과 같이 제한을 할 수 있습니다.
In [229]: foo[foo.b.str.match('(f.*)').str.len() > 0]
Out[229]:
a b
1 2 foo
2 3 fat
그래도 인위적으로 정규식에 그룹을 넣을 수 있으며 깨끗한 방법이 아닌 것 같습니다. 더 좋은 방법이 있습니까?
사용은 포함 대신 :
In [10]: df.b.str.contains('^f')
Out[10]:
0 False
1 True
2 True
3 False
Name: b, dtype: bool
데이터 프레임을 사용한 다중 열 검색 :
frame[frame.filename.str.match('*.'+MetaData+'.*') & frame.file_path.str.match('C:\test\test.txt')]
문자열 처리 기능이 이미 있습니다 Series.str.startswith()
. 당신은 시도해야합니다 foo[foo.b.str.startswith('f')]
.
결과:
a b
1 2 foo
2 3 fat
나는 당신이 기대하는 것을 생각합니다.
또는 regex 옵션과 함께 contains를 사용할 수 있습니다. 예를 들면 다음과 같습니다.
foo[foo.b.str.contains('oo', regex= True, na=False)]
결과:
a b
1 2 foo
na=False
nan, null 등의 값이있는 경우 오류를 방지하는 것입니다.
This may be a bit late, but this is now easier to do in Pandas. You can call match with as_indexer=True
to get boolean results. This is documented (along with the difference between match
and contains
) here.
Thanks for the great answer @user3136169, here is an example of how that might be done also removing NoneType values.
def regex_filter(val):
if val:
mo = re.search(regex,val)
if mo:
return True
else:
return False
else:
return False
df_filtered = df[df['col'].apply(regex_filter)]
Write a Boolean function that checks the regex and use apply on the column
foo[foo['b'].apply(regex_function)]
Using str
slice
foo[foo.b.str[0]=='f']
Out[18]:
a b
1 2 foo
2 3 fat
참고URL : https://stackoverflow.com/questions/15325182/how-to-filter-rows-in-pandas-by-regex
'development' 카테고리의 다른 글
java.lang.UnsupportedClassVersionError : .class 파일의 버전 번호가 잘못 되었습니까? (0) | 2020.06.21 |
---|---|
순환 객체 값을 포함하는 직렬화 객체 (0) | 2020.06.21 |
'str'오브젝트에는 'decode'속성이 없습니다. (0) | 2020.06.21 |
Internet Explorer는 pushState 및 replaceState를 지원합니까? (0) | 2020.06.21 |
백그라운드에서 Windows 예약 작업을 실행하려면 어떻게 설정합니까? (0) | 2020.06.21 |