Bri*_*tow 5 python sorting pandas
我有一个熊猫数据框,说:
df = pd.DataFrame ([['a', 3, 3], ['b', 2, 5], ['c', 4, 9], ['d', 1, 43]], columns = ['col 1' , 'col2', 'col 3'])
Run Code Online (Sandbox Code Playgroud)
或者:
col 1 col2 col 3
0 a 3 3
1 b 2 5
2 c 4 9
3 d 1 43
Run Code Online (Sandbox Code Playgroud)
如果我想按 col2 排序,我可以使用 df.sort,它将升序和降序排序。
但是,如果我想对行进行排序,使 col2 为:[4, 2, 1, 3],我该怎么做?
尝试这个:
sortMap = {4:1, 2:2, 1:3,3:4 }
df["new"] = df2['col2'].map(sortMap)
df.sort_values('new', inplace=True)
df
col1 col2 col3 new
2 c 4 9 1
1 b 2 5 2
3 d 1 43 3
0 a 3 3 4
Run Code Online (Sandbox Code Playgroud)
创建 dict 的 alt 方法:
ll = [4, 2, 1, 3]
sortMap = dict(zip(ll,range(len(ll))))
Run Code Online (Sandbox Code Playgroud)
一种方法是将该列转换为Categorical可以具有任意顺序的类型。
In [51]: df['col2'] = df['col2'].astype('category', categories=[4, 1, 2, 3], ordered=True)
In [52]: df.sort_values('col2')
Out[52]:
col 1 col2 col 3
2 c 4 9
3 d 1 43
1 b 2 5
0 a 3 3
Run Code Online (Sandbox Code Playgroud)