Pandasで行をグループ化する方法(groupby)

投稿者: | 2020年11月10日

Pandasで行をグループ化する方法(groupby)です

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列をグループ化してカウントを取得

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.groupby('b').count())

実行結果

    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  c  d  e  f  g  h  i  j
b
2   9  9  9  9  9  9  9  9  9
52  1  1  1  1  1  1  1  1  1

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

b列とc列をグループ化してカウント取得

print(df.groupby(['b', 'c']).count())

実行結果

       a  d  e  f  g  h  i  j
b  c
2  3   9  9  9  9  9  9  9  9
52 53  1  1  1  1  1  1  1  1