How to convert 'SeriesGroupBy' object to list

Question:

I have a dataframe with several columns that I am filtering in hopes of using the output to filter another dataframe further. Ultimately I’d like to convert the group by object to a list to further filter another dataframe but I am having a hard time converting the SeriesGroupBy object to a list of values. I am using:

id_list = df[df['date_diff'] == pd.Timedelta('0 days')].groupby('id')['id'].tolist()

I’ve tried to reset_index() and to_frame() and .values before to_list() with no luck.

error is:
‘SeriesGroupBy’ object has no attribute tolist

Expected output: Simply a list of id’s

Asked By: bbal20

||

Answers:

Try –

pd.Timedelta('0 days')].groupby('id')['id'].apply(list)

Also, I am a bit skeptical about how you are comparing df['date_diff'] with the groupby output.


EDIT: This might be useful for your intended purpose (s might be output of your groupby):

s = pd.Series([['a','a','b'],['b','b','c','d'],['a','b','e']])

s.explode().unique().tolist()
['a', 'b', 'c', 'd', 'e']
Answered By: Akshay Sehgal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.