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
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']
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
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']