0
1

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.DataFrameの行を複数条件で抽出する

Last updated at Posted at 2020-12-03

きっかけ

pandasいじる時に毎回複数条件でデータをフィルタリングかける方法を忘れてしまうので記事にしてしまおうと思い、記しておきます。

データはこんな感じです。

import pandas as pd

d = {'ID': [1, 2], 'Name': ['Shota', 'James'], 'Country': ['Japan', 'America']}
df = pd.DataFrame(data=d)
ID Name Country
1 Shota Japan
2 James America

pandasで複数条件を連結させる時は&や|を使います。各条件は括弧で括っておく。

df[(df.Name=='Shota') & (df.Country=='Japan')]
df.loc[(df.Name=='Shota') & (df.Country=='Japan')] # こっちでも一緒

df[(df.Name=='Shota') | (df.Country=='Japan')]
df.loc[(df.Name=='Shota') | (df.Country=='Japan')] # こっちでも一緒

否定条件を作りたい時は、括弧の外側に~を置く。もちろん、括弧内の==を!=に置き換えるだけでも問題ない。

df[~(df.Name=='James') & ~(df.Country=='America')]
df.loc[~(df.Name=='James') & ~(df.Country=='America')] # こっちでも一緒

ちなみに上で記載したコードの結果は全て下記になる。

ID Name Country
1 Shota Japan
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?