我有一个数据框“df”,它包含:
col1 = datetime[64]
col2 = object
col3 = object
col4 = object
我想按“col1”对数据框进行排序。然后我想按“col2”分组。最后,我想在该分组中按“col2”创建一个序数值 (1,2,3),并按“col1”排序。如果按“col2”分组的行中有 4 行,那么在这个新列中,这些行的值将为 [1,2,3,4]。
我知道 PANDA 中有一个 'rank()',我可以使用
df['newcol'] = df.groupby(['col2'])['col1'].rank()
但这并没有给我原始的数据框列,其序数值仅在分组内类似于 [1,2,3]?
请您参考如下方法:
您是否正在努力实现这样的目标?没有样本数据和预期结果很难判断。
random.seed(0)
df = pd.DataFrame({col: [random.choice(list('abc')) for i in range(10)] for col in list('ABC')})
df['timestamp'] = pd.date_range('2016-1-1', periods=len(df))
df.sort_values('timestamp', inplace=True)
df['rank'] = \
df.groupby('A')['B'].transform(lambda group: group.astype('category').cat.codes + 1)
>>> df
A B C timestamp rank
0 c c a 2016-01-01 2
1 c b c 2016-01-02 1
2 b a c 2016-01-03 1
3 a c c 2016-01-04 1
4 b b b 2016-01-05 2
5 b a a 2016-01-06 1
6 c c b 2016-01-07 2
7 a c b 2016-01-08 1
8 b c c 2016-01-09 3
9 b c c 2016-01-10 3
