pandasソートとランキング
2395 ワード
条件に基づいてデータをソートすることは重要な内蔵演算である.行または列をソートするにはsort_を使用します(辞書順).indexメソッドは、ソートされた新しいオブジェクトを返します.
byに値を割り当て、1つ以上の行列の値に基づいてソートします.
優先順位による複数の列のソート
行のソート
ランキングrank()
method
説明
‘average’
≪デフォルト|Default|oem_src≫:「≪等しいグループ|Iso Group|oem_src≫」で、各値に平均順位を割り当てます.
‘min’
グループ全体の最小順位の使用
‘max’
グループ全体の最大順位の使用
‘first’
元のデータに値が表示される順序でランク付け
同様に、DataFrameでもランク付けが可能です
frame= DataFrame(np.arange(8).reshape(2,4),
index=['one','two'],columns=[list('dabc')])
frame
Out[5]:
d a b c
one 0 1 2 3
two 4 5 6 7
frame.sort_index()
Out[9]:
d a b c
one 4 5 6 7
two 0 1 2 3
frame.sort_index(axis=1)
Out[11]:
a b c d
two 1 2 3 0
one 5 6 7 4
frame.sort_index(axis=1,ascending=False)#
Out[12]:
d c b a
two 0 3 2 1
one 4 7 6 5
byに値を割り当て、1つ以上の行列の値に基づいてソートします.
f2 = DataFrame({'b':[4,7,-3,2],'a':[0,1,0,1]})
f2
Out[55]:
b a
0 4 0
1 7 1
2 -3 0
3 2 1
f2.sort_index(by='b')
__main__:1: FutureWarning: by argument to sort_index is deprecated,
please use .sort_values(by=...)
Out[59]:
b a
2 -3 0
3 2 1
0 4 0
1 7 1
# .sort_values(by=...
f2.sort_values(by='b')
Out[60]:
b a
2 -3 0
3 2 1
0 4 0
1 7 1
優先順位による複数の列のソート
f2.sort_values(by=['a','b'])
Out[61]:
b a
2 -3 0
0 4 0
3 2 1
1 7 1
f2.sort_values(by=['b','a'])
Out[62]:
b a
2 -3 0
3 2 1
0 4 0
1 7 1
行のソート
f2.sort_values(by=[1],axis=1)
Out[64]:
a b
0 0 4
1 1 7
2 0 -3
3 1 2
f2.sort_values(by=[1,2],axis=1)
Out[65]:
a b
0 0 4
1 1 7
2 0 -3
3 1 2
ランキングrank()
obj
Out[66]:
0 7
1 -5
2 7
3 4
4 2
5 0
6 4
dtype: int64
method
説明
‘average’
≪デフォルト|Default|oem_src≫:「≪等しいグループ|Iso Group|oem_src≫」で、各値に平均順位を割り当てます.
‘min’
グループ全体の最小順位の使用
‘max’
グループ全体の最大順位の使用
‘first’
元のデータに値が表示される順序でランク付け
obj.rank()
Out[67]:
0 6.5
1 1.0
2 6.5
3 4.5
4 3.0
5 2.0
6 4.5
dtype: float64
obj.rank(method='min')
Out[69]:
0 6.0
1 1.0
2 6.0
3 4.0
4 3.0
5 2.0
6 4.0
dtype: float64
obj.rank(method='max')
Out[70]:
0 7.0
1 1.0
2 7.0
3 5.0
4 3.0
5 2.0
6 5.0
dtype: float64
obj.rank(method='first',ascending=False)
Out[71]:
0 1.0
1 7.0
2 2.0
3 3.0
4 5.0
5 6.0
6 4.0
dtype: float64
同様に、DataFrameでもランク付けが可能です