2017-10-26 8 views
0

私はstr.findallとstr.matchの両方をいつ使うのか混乱します。パンダの正規表現:Matchall対Findall

たとえば、私は日付を抽出する必要がある多くの行のテキストを持つdfを持っています。

私は、作品Marがある行をチェックしたいとしましょう(Marchの略語として)。私は試合

df[df.original.str.match(r'(Mar)')==True] 

があるDFを放送する場合、私は、私は次の出力だ

:私はstr.findall内の同じ正規表現をしようとした場合、しかし、

204 Mar 10 1976 CPT Code: 90791: No medical servic... 
299 March 1974 Primary ... 

を、私は何もありません:

0  [] 
1  [] 
2  [] 
3  [] 
4  [] 
5  [] 
6  [] 
7  [] 
... 

495    [] 
496    [] 
497    [] 
498    [] 
499    [] 
Name: original, Length: 500, dtype: object 

なぜですか?私はそれがマッチ、find、findall、extractとextractallの理解の欠如であると確信しています。

答えて

1

私はこれを説明する文書を使用しよう:

s = pd.Series(["a1a2", "b1", "c1"], index=["A", "B", "C"]) 
s 

出力:

A a1a2 
B  b1 
C  c1 
dtype: object 

我々が最初にこのようにシリーズを行い、その後、extract,extractall,find,findall

s.str.extract("([ab])(\d)",expand=True)#We could use the extract and give the pat which can be str of regx 
and only return the first match of the results. 

    0 1 
A a 1 
B b 1 
C NaN NaN 

s.str.extractall("([ab])(\d)")#return all the detail which me match 

     0 1 
match  
A 0 a 1 
1 a 2 
B 0 b 1 

s.str.find("([ab])(\d)")#all the values is -1 cause find can only give the string 

s.str.find('a') 
A 0 
B -1 
C -1 
dtype: int64 

s.str.findall("([ab])(\d)")#give a string or regx and return the detail result 
A [(a, 1), (a, 2)] 
B   [(b, 1)] 
C     [] 
dtype: object 
を使用