(pandas)sort_index()与sort_values()的使用

在Series与DataFrame中数据的排序


sort_index()方法在指定轴上根据索引进行排序

sort_index(axis=0, ascending=True, inplace=True)
axis:1轴,0轴(默认)。
ascending:默认True升序,False降序。
inplace:默认为False,删除重复项后返回副本。True,直接在原数据上删除重复项。

# 初始的Series,DataFrame
series = pd.Series(np.arange(4), index=['a','c','d','b'])
df = pd.DataFrame(np.arange(20).reshape(4,5), index=['a','c','d','b'])

a    0
c    1
d    2
b    3

    0   1   2   3   4
a   0   1   2   3   4
c   5   6   7   8   9
d  10  11  12  13  14
b  15  16  17  18  19

series.sort_index(axis=0, ascending=True, inplace=True)
df.sort_index(axis=0, ascending=True, inplace=True)
a    0
b    3
c    1
d    2

    0   1   2   3   4
a   0   1   2   3   4
b  15  16  17  18  19
c   5   6   7   8   9
d  10  11  12  13  14

sort_index())方法在指定轴上根据数据进行排序,(NAN统一排在最后)

sort_values(axis=0, by=[1], ascending=True, inplace=True)
axis:1轴,0轴(默认)。
by:int,str,list等,当axis=0,by=[‘列名’];当axis=1,by=[‘行名’]。
ascending:默认True升序,False降序。
inplace:默认为False,删除重复项后返回副本。True,直接在原数据上删除重复项。

series.sort_values(ascending=False, inplace=True)

b    3
d    2
c    1
a    0

# by根据指定列的值排序
df.sort_values(axis=0, by=[1], ascending=False, inplace=True)

    0   1   2   3   4
b  15  16  17  18  19
d  10  11  12  13  14
c   5   6   7   8   9
a   0   1   2   3   4

# by根据指定行的值排序
df.sort_values(axis=1, by=['a'], ascending=False, inplace=True)

    4   3   2   1   0
a   4   3   2   1   0
c   9   8   7   6   5
d  14  13  12  11  10
b  19  18  17  16  15
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream丶Killer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值