如何将pandas中的GroupBy对象转换为多索引数据框架



我有一个原始数据框架,看起来像

codcet  placa_encoded   date   time_seconds velocidade
5031 490191222  431.0      2021-03-11   70079.0      51
5032 490221211  431.0      2021-03-11   72219.0      55
7991 490361213  562.0      2021-03-11   28559.0      24
7992 490361232  562.0      2021-03-11   29102.0      29              
7993 490361221  562.0      2021-03-11   30183.0      33                 
...

其中最左边的数字是原始数据集的索引。我的目标是将其转换为由placa_encodedn索引的数据帧,每个组中的计数器看起来像

placa_encoded  n    time_seconds  velocidade            codcet    
431.0          0      70079.0           51              490191222   
431.0          1      72219.0           55              490221211   
562.0          0      28559.0           24              490361213   
562.0          1      29102.0           29              490361232
562.0          2      30183.0           33              490361221   

也就是说,我的目标是groupby('placa_encoded'),然后添加另一列n,计算每个组中的位置。行应该同时被placa_encodedn索引。我想我可以使用cumcount()来做到这一点,但我不清楚如何将其添加为一列,因为groupby不产生我可以分配的数据框。我看了看这个问题,但似乎他们使用.count()将其转换为数据框,我想保留数据,而不是得到任何计数。我还尝试使用pd.DataFrame(gbplaca)pd.DataFrame(gbplaca.groups),但无济于事。

非常感谢!

我想这就是你想要的

df['n'] = df.sort_values(['time_seconds'], ascending=True).groupby(['placa_encoded']).cumcount()
df = df.set_index(['placa_encoded', 'n'])
df

这是一个带有'placa_encoded'和'n'的多重索引

您所要做的就是将df中的列(命名为'n')与df.groupby('placa_encoded').cumcount()的结果设置为:

df.loc[:, 'n'] = df.groupby('placa_encoded').cumcount()
print(df)
codcet  placa_encoded        date  time_seconds  velocidade  n
0  490191222          431.0  2021-03-11       70079.0          51  0
1  490221211          431.0  2021-03-11       72219.0          55  1
2  490361213          562.0  2021-03-11       28559.0          24  0
3  490361232          562.0  2021-03-11       29102.0          29  1
4  490361221          562.0  2021-03-11       30183.0          33  2

如果需要,可以将df的多索引设置为['placa_encoded', 'n']:

df = df.set_index(['placa_encoded', 'index'])
print(df)
codcet        date  time_seconds  velocidade
placa_encoded n                                                 
431.0         0  490191222  2021-03-11       70079.0          51
1  490221211  2021-03-11       72219.0          55
562.0         0  490361213  2021-03-11       28559.0          24
1  490361232  2021-03-11       29102.0          29
2  490361221  2021-03-11       30183.0          33

最新更新