python中sort的用法,在Python中使用key的sort_values()

I have a dataframe where the column names are times (0:00, 0:10, 0:20, ..., 23:50). Right now, they're sorted in a string order (so 0:00 is first and 9:50 is last) but I want to sort them after time (so 0:00 is first and 23:50 is last).

If time is a column, you can use

df = df.sort(columns='Time',key=float)

But 1) that only works if time is a column itself, rather than the column names, and 2) sort() is deprecated so I try to abstain from using it.

I'm trying to use

df = df.sort_index(axis = 1)

but since the column names are in string format, they get sorted according to a string key. I've tried

df = df.sort_index(key=float, axis=1)

but that gives an error message:

Traceback (most recent call last):

File "", line 1, in

df.sort_index(key=float, axis=1)

TypeError: sort_index() got an unexpected keyword argument 'key'

Does anyone have ideas for how to fix this? So annoying that sort_index() - and sort_values() for that matter - don't have the key argument!!

解决方案

Try sorting the columns with the sorted builtin function and passing the output to the dataframe for indexing. The following should serve as a working example:

import pandas as pd

records = [(2, 33, 23, 45), (3, 4, 2, 4), (4, 5, 7, 19), (4, 6, 71, 2)]

df = pd.DataFrame.from_records(records, columns = ('0:00', '23:40', '12:30', '11:23'))

df

# 0:00 23:40 12:30 11:23

# 0 2 33 23 45

# 1 3 4 2 4

# 2 4 5 7 19

# 3 4 6 71 2

df[sorted(df,key=pd.to_datetime)]

# 0:00 11:23 12:30 23:40

# 0 2 45 23 33

# 1 3 4 2 4

# 2 4 19 7 5

# 3 4 2 71 6

I hope this helps

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值