Pandasでソートする方法(sort_values)

投稿者: | 2020年11月4日

Pandasでソートする方法(sort_values)です

csvファイル

10,2,3,4,5,6,7,8,9,10
9,2,3,4,5,6,7,8,9,10
8,2,3,4,5,6,7,8,9,10
7,2,3,4,5,6,7,8,9,10
6,2,3,4,5,6,7,8,9,10
5,2,3,4,5,6,7,8,9,10
4,2,3,4,5,6,7,8,9,10
3,2,3,4,5,6,7,8,9,10
2,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10

csvファイルを読み込み、1列目を昇順でソート

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.sort_values(by=['a'], ascending=True))

結果

    a  b  c  d  e  f  g  h  i   j
9   1  2  3  4  5  6  7  8  9  10
8   2  2  3  4  5  6  7  8  9  10
7   3  2  3  4  5  6  7  8  9  10
6   4  2  3  4  5  6  7  8  9  10
5   5  2  3  4  5  6  7  8  9  10
4   6  2  3  4  5  6  7  8  9  10
3   7  2  3  4  5  6  7  8  9  10
2   8  2  3  4  5  6  7  8  9  10
1   9  2  3  4  5  6  7  8  9  10
0  10  2  3  4  5  6  7  8  9  10

csvファイルを読み込み、1列目を降順でソート

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.sort_values(by=['a'], ascending=False))

結果

    a  b  c  d  e  f  g  h  i   j
0  10  2  3  4  5  6  7  8  9  10
1   9  2  3  4  5  6  7  8  9  10
2   8  2  3  4  5  6  7  8  9  10
3   7  2  3  4  5  6  7  8  9  10
4   6  2  3  4  5  6  7  8  9  10
5   5  2  3  4  5  6  7  8  9  10
6   4  2  3  4  5  6  7  8  9  10
7   3  2  3  4  5  6  7  8  9  10
8   2  2  3  4  5  6  7  8  9  10
9   1  2  3  4  5  6  7  8  9  10

ソートの項目を増やす場合

df.sort_values(by=['a', 'b'], ascending=[False, True]