bongbang
bongbang

Reputation: 1712

Listify indices according to column groupby

My question is similar to "grouping rows in list in pandas groupby", but what is to be listified is the index, not just another column.

I know I can turn the index into just another column with reset_index(), but I spent a lot of time trying to capture the index field directly. Is there a way?

Example:

df = pd.DataFrame({'a':['A','A','B','B','B','C'], 'b':[1,2,5,5,4,6]})
df.reset_index().groupby('a')['index'].apply(list)

Output:

A       [0, 1]
B    [2, 3, 4]
C          [5]

Upvotes: 1

Views: 86

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Try:

df.index.to_series().groupby(df['a']).apply(list)

Output:

a
A       [0, 1]
B    [2, 3, 4]
C          [5]
dtype: object

Upvotes: 1

sammywemmy
sammywemmy

Reputation: 28644

Use a list comprehension to iterate through the groups, and create a new dataframe

(pd.DataFrame([(name,group.index.tolist())
                for name, group in df.groupby('a')],
                columns=['name','index'])
 )

    name    index
0   A   [0, 1]
1   B   [2, 3, 4]
2   C   [5]

Upvotes: 1

Related Questions