首先过滤所有
duplicated行,然后
groupby使用
apply或转换
index
to_series:
df = df[df.col.duplicated(keep=False)]a = df.groupby('col').apply(lambda x: list(x.index))print (a)col1 [1, 3, 4]2 [2, 5]dtype: objecta = df.index.to_series().groupby(df.col).apply(list)print (a)col1 [1, 3, 4]2 [2, 5]dtype: object
如果需要嵌套列表:
L = df.groupby('col').apply(lambda x: list(x.index)).tolist()print (L)[[1, 3, 4], [2, 5]]如果需要使用,只能通过位置选择第一列
iloc:
a = df[df.iloc[:,0].duplicated(keep=False)] .groupby(df.iloc[:,0]).apply(lambda x: list(x.index))print (a)col1 [1, 3, 4]2 [2, 5]dtype: object



