<Python, pandas> 対象の値の要素を選択 (grep)

データフレームDataFrame中で、見つけたい文字Stringがある場合。
.isin()を使う。
検索する値は、リストlistで渡す。
ちなみに、正規表現regexpは効かないっぽい。
値が完全に一致するものを見つけにいってる。

In [150]: df
Out[150]: 
   a   b        c
0  a  ab        x
1  b  bb  abcdefe
2  c  bc        z

In [152]: df.isin(['a'])
Out[152]: 
       a      b  \
0   True  False   
1  False  False   
2  False  False   

       c  
0  False  
1  False  
2  False  

In [153]: df.isin(['ab'])
Out[153]: 
       a      b  \
0  False   True   
1  False  False   
2  False  False   

       c  
0  False  
1  False  
2  False  

In [154]: df.isin(['a', 'ab'])
Out[154]: 
       a      b  \
0   True   True   
1  False  False   
2  False  False   

       c  
0  False  
1  False  
2  False

あと、結果のTrueFalseを反転する場合は、~

In [155]: ~df.isin(['a', 'ab'])
Out[155]: 
       a      b  \
0  False  False   
1   True   True   
2   True   True   

       c  
0   True  
1   True  
2   True

じゃー、正規表現したい場合は、
.applymap()re.matchbool()で対応。

In [157]: df.applymap(lambda x: bool(re.match('a', x)))
Out[157]: 
       a      b  \
0   True   True   
1  False  False   
2  False  False   

       c  
0  False  
1   True  
2  False  

シリーズSeriesだったら、.str.contains()でいいんだけど、

In [158]: df['a'].str.contains('a')
Out[158]: 
0     True
1    False
2    False
Name: a, dtype: bool

過去記事も。

nekoyukimmm.hatenablog.com