基于唯一ID Pandas数据帧收集行



我有一个大型时间序列数据集,其中一些观测值(每个观测值都有一个唯一的ID(具有不同的长度。我还有一个"Section"列,它为每个唯一的ID计数时间步或行。

df.groupby([df['ID']]).agg({'count'})
A             B                         Z
count         count         ...         count   
ID                                                        
25782                          194           194                      194   
25783                          198           198                      198   
25784                          194           194                      194   
25785                          192           192                      192   
...                             ...           ...          ...          ...
25787                          192           192                      192   
25788                          195           195                      195   
25789                          196           196                      196   
25790                          200           200                      200   

比如我想创建一个新的数据帧,该数据帧仅由唯一ID=192的长度组成。I.e"区段"总计192。

到目前为止,我已经尝试了以下方法,但没有成功。请帮忙。

mask = df.groupby('ID')(len(df['Section']) == 192)
df = df.loc[mask]
print(df)

df.groupby('ID').df[df['Section'].max() == 192]

编辑

所需输出

new_df.groupby([new_df['ID']]).agg({'count'})
A             B                         Z
count         count         ...         count   
ID                                                        
25752                          192           192                      192   
25137                          192           192                      192   
25970                          192           192                      192   
25440                          192           192                      192  

您可以在groupby之后使用filter,只保留"Section"列长度为192的ID,例如:

new_df = df.groupby('ID').filter(lambda x: len(x['Section']) == 192)

然后当你做new_df.groupby('ID').agg({'count'})时,你应该得到你期望的输出

最新更新