16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pandasで特定の文字列を含む/含まない行を抽出

Last updated at Posted at 2020-01-17

型が文字列のpandas DataFrameに対して、ある特定の文字列を含む行や含まない行を抽出する方法をメモします。
まず、こういうデータを準備します。

データの定義
>>> df = pd.DataFrame ({"col_A":["dataA_1","dataA_2","dataA_3","dataA_4"],"col_B":["dataB_1","dataB_2","dataB_3","dataB_4"]})
>>> df
     col_A    col_B
0  dataA_1  dataB_1
1  dataA_2  dataB_2
2  dataA_3  dataB_3
3  dataA_4  dataB_4

で、col_Aに特定の文字列が含まれる行を調べるには下記でいけます

特定の文字列を含む場合の条件抽出
>>> df[df['col_A'].str.contains('A_1')]
     col_A    col_B
0  dataA_1  dataB_1

なぜなら

特定の文字列を含む場合の条件抽出
>>> df['col_A'].str.contains('A_1')
0     True
1    False
2    False
3    False

だからです。

で、一方、col_Aに特定の文字列が含まれない行を調べるには下記でいけます.

特定の文字列を含まない場合の条件抽出
>>> df[~df['col_A'].str.contains('A_1')]
     col_A    col_B
1  dataA_2  dataB_2
2  dataA_3  dataB_3
3  dataA_4  dataB_4

なぜなら"~"をつけると反転するからです。

解説
>>> df['col_A'].str.contains('A_1')
0     True
1    False
2    False
3    False
Name: col_A, dtype: bool
>>> ~df['col_A'].str.contains('A_1')
0    False
1     True
2     True
3     True
Name: col_A, dtype: bool

[数字の場合はこちら][1]
[1]:https://qiita.com/NP_Systems/items/05a79e0372bf9c9003e5

NP-Sytems( https://np-sys.com )。 

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?