9
6

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-02-08

サンプルデータとコードです。 groupby とrank の操作例です。

サンプルデータ

data=[
{"氏名":"山田","回数":1, "国語":10 ,"算数":20 },
{"氏名":"山田","回数":2, "国語":20 ,"算数":30 },
{"氏名":"山田","回数":3, "国語":30 ,"算数":40 },
{"氏名":"山田","回数":4, "国語":40 ,"算数":50 },

{"氏名":"鈴木","回数":1, "国語":10 ,"算数":50 },
{"氏名":"鈴木","回数":2, "国語":20 ,"算数":40 },
{"氏名":"鈴木","回数":3, "国語":30 ,"算数":30 },
{"氏名":"鈴木","回数":4, "国語":40 ,"算数":20 },
    
{"氏名":"野田","回数":1, "国語":10 ,"算数":30 },
{"氏名":"野田","回数":2, "国語":20 ,"算数":40 },
{"氏名":"野田","回数":3, "国語":30 ,"算数":20 },
{"氏名":"野田","回数":4, "国語":40 ,"算数":50 },
]

import pandas as pd
df=pd.DataFrame(data)
print(df.to_markdown()) 
氏名 回数 国語 算数
0 山田 1 10 20
1 山田 2 20 30
2 山田 3 30 40
3 山田 4 40 50
4 鈴木 1 10 50
5 鈴木 2 20 40
6 鈴木 3 30 30
7 鈴木 4 40 20
8 野田 1 10 30
9 野田 2 20 40
10 野田 3 30 20
11 野田 4 40 50

回数別の算数上位者を求める。(groupby とrank のサンプル)

import pandas as pd
df=pd.DataFrame(data)
# print(df.to_markdown()) 

# 回数別の算数上位者
df["回数別算数順位"]=df.groupby(["回数"])["算数"].rank(ascending=False)

# 見やすいように表示順、カラム位置を修正
df.sort_values(["回数","回数別算数順位"],inplace=True)
df=df[[ '回数' , '回数別算数順位' , '算数' , '氏名'  ]]

print(df.to_markdown()) 

結果

回数 回数別算数順位 算数 氏名
4 1 1 50 鈴木
8 1 2 30 野田
0 1 3 20 山田
5 2 1.5 40 鈴木
9 2 1.5 40 野田
1 2 3 30 山田
2 3 1 40 山田
6 3 2 30 鈴木
10 3 3 20 野田
3 4 1.5 50 山田
11 4 1.5 50 野田
7 4 3 20 鈴木

参考

pandas.core.groupby.DataFrameGroupBy.rank

9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?