Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas GroupBy get list of groups

Tags:

python

pandas

I have a line of code:

g = x.groupby('Color') 

The colors are Red, Blue, Green, Yellow, Purple, Orange, and Black. How do I return this list? For similar attributes, I use x.Attribute and it works fine, but x.Color doesn't behave the same way.

like image 307
user3745115 Avatar asked Mar 04 '15 00:03

user3745115


People also ask

How can I see my groups in pandas?

By doing groupby() pandas returns you a dict of grouped DFs. You can easily get the key list of this dict by python built in function keys() .

How do you list on Groupby?

You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.

How do I get Groupby columns in pandas?

You can also reset_index() on your groupby result to get back a dataframe with the name column now accessible. If you perform an operation on a single column the return will be a series with multiindex and you can simply apply pd. DataFrame to it and then reset_index. Show activity on this post.


1 Answers

There is much easier way of doing it:

g = x.groupby('Color')  g.groups.keys() 

By doing groupby() pandas returns you a dict of grouped DFs. You can easily get the key list of this dict by python built in function keys().

like image 51
Yanqi Ma Avatar answered Sep 25 '22 19:09

Yanqi Ma