Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

KeyError whlie grouping

I have a DataFrame (df) of size (1000, 5). I want to groupby it into 10 equal groups.

First 100 rows should fall into the first group, and so on.

I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

res = df.groupby(100) 

KeyError: 100

How can I do it guys?

Also, want to get [1,5,6,7] groups.

>Solution :

Try this:

res = df.groupby(np.arange(len(df))//(df.shape[0]//10))

To get the first three groups into a df, one option is to slice your original df.

n = 3
df.iloc[:(df.shape[0]//10)*n]

Another option is to create a dictionary which contains all the groups of your original groupby and join that. This will allow you to specify the groups using keys:

g = [1,5,6,7]
pd.concat({e:v for e,(k,v) in enumerate(res,1)},keys = g)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading