<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
あと、結果のTrue
とFalse
を反転する場合は、~
。
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.match
+bool()
で対応。
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