Pandasで行を条件で取得する方法(query)

投稿者: | 2020年11月9日

Pandasで行を条件で取得する方法(query)です

csvファイル

1,2,3,4,5,6,7,8,9,10
2,2,3,4,5,6,7,8,9,11
3,2,3,4,5,6,7,8,9,10
4,2,3,4,5,6,7,8,9,10
5,52,53,54,55,56,57,58,59,50
6,2,3,4,5,6,7,8,9,10
7,2,3,4,5,6,7,8,9,10
8,2,3,4,5,6,7,8,9,10
9,2,3,4,5,6,7,8,9,10
10,2,3,4,5,6,7,8,9,10

b列が2でj列が11以外の行を取得

import pandas as pd

file = r'csvファイルのパス'
df = pd.read_csv(file, header=None, names=('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'))
print(df)
print(df.query("b == 2 & not(j==11)"))

実行結果

    a   b   c   d   e   f   g   h   i   j
0   1   2   3   4   5   6   7   8   9  10
1   2   2   3   4   5   6   7   8   9  11
2   3   2   3   4   5   6   7   8   9  10
3   4   2   3   4   5   6   7   8   9  10
4   5  52  53  54  55  56  57  58  59  50
5   6   2   3   4   5   6   7   8   9  10
6   7   2   3   4   5   6   7   8   9  10
7   8   2   3   4   5   6   7   8   9  10
8   9   2   3   4   5   6   7   8   9  10
9  10   2   3   4   5   6   7   8   9  10
    a  b  c  d  e  f  g  h  i   j
0   1  2  3  4  5  6  7  8  9  10
2   3  2  3  4  5  6  7  8  9  10
3   4  2  3  4  5  6  7  8  9  10
5   6  2  3  4  5  6  7  8  9  10
6   7  2  3  4  5  6  7  8  9  10
7   8  2  3  4  5  6  7  8  9  10
8   9  2  3  4  5  6  7  8  9  10
9  10  2  3  4  5  6  7  8  9  10

(12行目~20行目が取得した結果)

b列が2でj列が11以外の行カウントを取得

print(df.query("b == 2 & not(j==11)").count())

実行結果

a    8
b    8
c    8
d    8
e    8
f    8
g    8
h    8
i    8
j    8