Skip to content Skip to sidebar Skip to footer

Grouping In Pandas

I want to group data in a dataframe I have oo the Column 'Count' and by another column 'State'. I would like to output a list of list, each sub set list would just be the count for

Solution 1:

It is possible as a one-liner:

import pandas as pd                                                                           

df = pd.DataFrame.from_dict({"State": ["ny", "or", "ny", "nm"],                     
                             "Counts": [100,300,200,400]})

list_new = df.groupby("State")["Counts"].apply(list).tolist()
print(list_new)

[[400], [100, 200], [300]]

You should read the doc of groupby to see what the expected outcome of the grouping is and how to change that (http://pandas.pydata.org/pandas-docs/stable/groupby.html).

Post a Comment for "Grouping In Pandas"