pandas的排序和排名

有的时候我们可以要根据索引的大小或者值的大小对Series和DataFrame进行排名和排序。

一、排序

pandas提供了sort_index方法可以根据行或列的索引按照字典的顺序进行排序

a、Series排序

1、按索引进行排序

    #定义一个Series
    s = Series([1,2,3],index=["a","c","b"])
    #对Series的索引进行排序,默认是升序
    print(s.sort_index())
    '''
    a    1
    b    3
    c    2
    '''
    #对索引进行降序排序
    print(s.sort_index(ascending=False))
    '''
    c    2
    b    3
    a    1
    '''

2、按值进行排序

    s = Series([np.nan,1,7,2,0],index=["a","c","e","b","d"])
    #对Series的值进行排序,默认是按值的升序进行排序的
    print(s.sort_values())
    '''
    d    0.0
    c    1.0
 

你可能感兴趣的:(pandas修炼之路,pandas入门教程)