pandas排序

pandas排序


pandas支持三种排序方式:

  • sorting by index labels
  • sorting by column values
  • sorting by a combination of both

By index

series.sort_indexDataFrame.sort_index()方法被用来根据index排序pandas对象。

import numpy as np
import pandas as pd
df = pd.DataFrame({
    'one':pd.Series(np.random.randn(3),index=['a','b','c']),
     'two': pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),
     'three': pd.Series(np.random.randn(3), index=['b', 'c', 'd'])                                       
})
unsorted_df = df.reindex(index=['a','d','c','b'],
                                columns=['three','teo','one'])
unsorted_df
threeteoone
aNaNNaN1.474084
d2.021092NaNNaN
c0.057446NaN-0.085553
b0.705659NaN-0.101295
unsorted_df.sort_index()
threeteoone
aNaNNaN1.474084
b0.705659NaN-0.101295
c0.057446NaN-0.085553
d2.021092NaNNaN
unsorted_df.sort_index(ascending=False)
threeteoone
d2.021092NaNNaN
c0.057446NaN-0.085553
b0.705659NaN-0.101295
aNaNNaN1.474084
unsorted_df.sort_index(axis=1) # 设置排序的轴
oneteothree
a1.474084NaNNaN
dNaNNaN2.021092
c-0.085553NaN0.057446
b-0.101295NaN0.705659

By values

Series.sort_values()方法按照Series的值排序。

DataFrame.sort_values()方法按照其columns或rows的值排序。

df1 = pd.DataFrame({
    'one':[2,1,1,1],
    'two':[1,2,3,4],
    'three':[5,4,3,2]
})
df1.sort_values(by='two')
onetwothree
0215
1124
2133
3142
df1.sort_values(by=['one','two'])
onetwothree
1124
2133
3142
0215

这些方法通过na_position参数对NA值进行特殊处理:

 s = pd.Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])
s[2] = np.nan
s.sort_values()
0      a
1      a
4      a
5      a
9      a
3      b
7      c
8      d
2    NaN
6    NaN
dtype: object
s.sort_values(na_position='first')
2    NaN
6    NaN
0      a
1      a
4      a
5      a
9      a
3      b
7      c
8      d
dtype: object

By indexes and values

作为by参数传递给DataFrame.sort_values()的字符串可以引用列名或索引级名。

 idx = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('a', 2),('b', 2), ('b', 1), ('b', 1)])
idx.names = ['first', 'second']
idx
MultiIndex([('a', 1),
            ('a', 2),
            ('a', 2),
            ('b', 2),
            ('b', 1),
            ('b', 1)],
           names=['first', 'second'])
df_multi = pd.DataFrame({'A': np.arange(6, 0, -1)},index=idx)
df_multi
A
firstsecond
a16
25
24
b23
12
11
df_multi.sort_values(by=['second', 'A'])
A
firstsecond
b11
12
a16
b23
a24
25

如果字符串与列名和索引级名称都匹配,则会发出警告,并且列优先。

搜索排序

Series的serachsorted()方法工作方式与numpy.ndarray.serachsorted()方法类似。

该方式表示将传入的数组的每一个元素插入到Series对象中,返回插入的位置。(实际上并没有插入Serives,只是求,如果插入,那么插入的位置是什么。)

ser = pd.Series([1, 2, 3])
ser.searchsorted([0,3])
array([0, 2], dtype=int64)
ser.searchsorted([0, 4])
array([0, 3], dtype=int64)
ser.searchsorted([1, 3], side='right')
array([1, 3], dtype=int64)
ser.searchsorted([1, 3], side='left')
array([0, 2], dtype=int64)
ser = pd.Series([3, 1, 2])
ser.searchsorted([0, 3], sorter=np.argsort(ser))
array([0, 2], dtype=int64)

最小/最大值

Series有nsmallest()nlargest()方法,它们返回最大或者最小的前n个值。对于一个大的Series,大的速度要比排序整个Series要快的多。

s = pd.Series(np.random.permutation(10))

s
0    9
1    2
2    8
3    6
4    0
5    7
6    3
7    4
8    1
9    5
dtype: int32
s.sort_values()
4    0
8    1
1    2
6    3
7    4
9    5
3    6
5    7
2    8
0    9
dtype: int32
s.nsmallest(4)
4    0
8    1
1    2
6    3
dtype: int32
s.nlargest(3)
0    9
2    8
5    7
dtype: int32

DataFrame同样也有nlargest()nsmallist()方法

df = pd.DataFrame({
    'a':[-2,-1,1,10,8,11,-1],
    'b':list('abdceff'),
    'c':[1.,2.,4.,3.2,np.nan,3.,4.0]
})
df.nlargest(3,'a')
abc
511f3.0
310c3.2
48eNaN
df.nlargest(5,['a','c'])
abc
511f3.0
310c3.2
48eNaN
21d4.0
6-1f4.0

根据多重索引排序

当column是多重索引时,必须明确指明排序依据的levels。

df1
onetwothree
0215
1124
2133
3142
df1.columns = pd.MultiIndex.from_tuples([
    ('a','one'),
    ('a','two'),
    ('b','three')
])
df1
ab
onetwothree
0215
1124
2133
3142
df1.sort_values(by=('a','two'))
ab
onetwothree
0215
1124
2133
3142

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值