保留具有最大重叠的相似行 pandas 数据框

Keep similar rows pandas dataframe with maximum overlap

我有一个问题 看起来像(示例)的数据框:

   index  ID   time     value
   0      1     2h       10
   1      1     2.15h    15
   2      1     2.30h    5
   3      1     2.45h    24
   4      2     2.15h    6
   5      2     2.30h    12
   6      2     2.45h    18
   7      3     2.15h    2
   8      3     2.30h    1

我想保持 ID 行重叠的最大数量。 所以:

   index  ID   time    value
   1      1     2.15h   15
   2      1     2.30h    5
   4      2     2.15h    6
   5      2     2.30h   12
   7      3     2.15h    2
   8      3     2.30h    1

我知道我可以创建一个具有唯一时间的 df,然后将每个 ID 单独合并到它,然后保留每次都填充所有 ID 的所有行,但这是非常不切实际的。我看过但没有找到可能更聪明的方法的答案。有人知道如何使它更实用吗?

使用:

cols = df.groupby(['ID', 'time']).size().unstack().dropna(axis=1).columns

df = df[df['time'].isin(cols)]
print (df)
   ID   time  value
1   1  2.15h     15
2   1  2.30h      5
4   2  2.15h      6
5   2  2.30h     12
7   3  2.15h      2
8   3  2.30h      1

详情:

groupby and size, then reshape by unstack 的第一个聚合 DataFrame - NaN 是为非重叠值创建的:

print (df.groupby(['ID', 'time']).size().unstack())
time  2.15h  2.30h  2.45h   2h
ID                            
1       1.0    1.0    1.0  1.0
2       1.0    1.0    1.0  NaN
3       1.0    1.0    NaN  NaN

删除包含 dropna 的列并获取列名称:

print (df.groupby(['ID', 'time']).size().unstack().dropna(axis=1))
time  2.15h  2.30h
ID                
1       1.0    1.0
2       1.0    1.0
3       1.0    1.0

最后一个过滤器列表 isin and boolean indexing:

df = df[df['time'].isin(cols)]