【Pandas】DataFrame排序 sort_index // sort_values

构造数据

df = pd.DataFrame(
    data=[
        ['zs', 18, 1],
        ['ls', 17, 2],
        ['ww', 19, 2],
        ['zl', 19, 1]
    ],
    columns=['name', 'age', 'group'],
    index=[2, 1, 4, 5]
)
print('df:\n', df)

在这里插入图片描述

按索引排序(sort_index)

行索引排序

df.sort_index(
	ascending=True, # ascending=True --升序排序(默认);  ascending=False --降序排序
	inplace=True,	# 如果为True,则直接删除,对原df进行操作; 如果为False(默认),那么返回一个结果,不会对原df操作!
	axis=0,			# axis=0	--根据行索引排序(默认);  axis=1	--根据列索引排序
	key=None		# (默认)None,否则在排序之前对索引值应用键函数。
)
print('df:\n', df)

在这里插入图片描述

列索引排序

df.sort_index(
	ascending=True, # ascending=True --升序排序(默认);  ascending=False --降序排序
	inplace=True,	# 如果为True,则直接删除,对原df进行操作; 如果为False(默认),那么返回一个结果,不会对原df操作!
	axis=1,			# axis=0	--根据行索引排序(默认);  axis=1	--根据列索引排序
)
print('df:\n', df)

在这里插入图片描述
上述排序是根据字符串的排序方式进行的

参数key的用法

>>> df = pd.DataFrame({"a": [1, 2, 3, 4]}, index=['A', 'b', 'C', 'd'])
>>> df.sort_index()
   a
A  1
C  3
b  2
d  4
>>> df.sort_index(key=lambda x: x.str.lower())
   a
A  1
b  2
C  3
d  4
"""

按数据排序(sort_values)

sort_valuessort_index 参数相似,区别是多出一个by参数指定用来排序的行 或 列,by的值可以是字符串或数组。

给一组数据排序

根据age排序

df.sort_values(
	by='age',
	ascending=True, 
	inplace=True
)
print('df:\n', df)

在这里插入图片描述

给多组数据排序

先根据age排序,age相同的数据再根据group排序

df.sort_values(
	by=['age', 'group'],
	ascending=True, 
	inplace=True
)
print('df:\n', df)

在这里插入图片描述

给多组数据进行不同排序

先根据age升序排序,age相同的数据再根据group降序排序


df.sort_values(
	by=['age', 'group'],
	ascending=[True, False], 
	inplace=True
)
print('df:\n', df)

在这里插入图片描述

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

胡桃の壶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值