我有一个这样的数据框:
col_1 | serial_number | remaining time
B | 17 | 02:45
A | 02 | 02:00
C | 25 | 03:30
A | 03 | 03:00
B | 12 | 03:45
C | 07 | 01:30
C | 89 | 02:30
B | 45 | 01:45
A | 01 | 01:00
我想对剩余时间(顶部最低)进行排序,但是col_1应该分组。以下是上述数据框的样子。
col_1 | serial_number | remaining time
A | 01 | 01:00
A | 02 | 02:00
A | 03 | 03:00
C | 07 | 01:30
C | 89 | 02:30
C | 25 | 03:30
B | 45 | 01:45
B | 17 | 02:45
B | 12 | 03:45
我目前无法做到这一点。首先,我需要按剩余时间排序,然后将col_1组合在一起。
答案 0 :(得分:3)
您可以使用groupby
+ transform
df['remaining_time_group_min'] = df['remaining time'].groupby(df.col_1).transform(min)
创建一个新列,对于每个元素,该列具有其组的任何成员的最短时间。
在此之后,正如jdehesa在评论中建议的那样,您可以使用
df.sort_values(['remaining_time_group_min', 'remaining time'])
答案 1 :(得分:3)
创建列col_1
的{{3}}并排序:
cats = df.sort_values(['remaining time'])['col_1'].unique()
print (cats)
['A' 'C' 'B']
df['col_1'] = pd.Categorical(df['col_1'], categories=cats, ordered=True)
df = df.sort_values([ 'col_1', 'remaining time'])
print (df)
col_1 serial_number remaining time
8 A 01 01:00
1 A 02 02:00
3 A 03 03:00
5 C 07 01:30
6 C 89 02:30
2 C 25 03:30
7 B 45 01:45
0 B 17 02:45
4 B 12 03:45
<强>详细强>:
print (df['col_1'])
8 A
1 A
3 A
5 C
6 C
2 C
7 B
0 B
4 B
Name: col_1, dtype: category
Categories (3, object): [A < C < B]
答案 2 :(得分:2)
创建DataFrame
:
import pandas as pd
df = pd.DataFrame({'col_1':['B','A','C','A','B','C','C','B','A'], 'serial_number':[17,2,25,3,12,7,89,45,1],'remaining time':['02:45','02:00','03:30','03:00','03:45','01:30','02:30','01:45','01:00']})
df['remaining time'] = pd.to_datetime(df['remaining time'])
df['remaining time'] = [time.time() for time in df['remaining time']]
使用每组最短时间添加新列:
df['min time'] = df.groupby('col_1')['remaining time'].transform(min)
然后按新的最短时间排序,然后按实际剩余时间排序:
>>> df.sort_values(by=['min time','remaining time'])
col_1 remaining time serial_number min time
8 A 01:00:00 1 01:00:00
1 A 02:00:00 2 01:00:00
3 A 03:00:00 3 01:00:00
5 C 01:30:00 7 01:30:00
6 C 02:30:00 89 01:30:00
2 C 03:30:00 25 01:30:00
7 B 01:45:00 45 01:45:00
0 B 02:45:00 17 01:45:00
4 B 03:45:00 12 01:45:00