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

How to copy all the rows having same ID from one pandas dataframe to another?

so I have a lot of rows in my pandas dataframe and I want to make a new dataframe containing all the rows for each differnet ID present in my dataframe.

this is the basic layout of the data that i have

ID name score
1 a Three
1 b Three
2 c Three
1 d Three
3 e Three
5 f Three

and this is what i am trying to get

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

ID name score
1 a Three
1 b Three
1 d Three

and so on for each and every ID.
Please help.

>Solution :

Just use list comprehension with groupby:

dataframes = [d for _, d in df.groupby('ID')]

Output:

>>> dataframes
[   ID name  score
 0   1    a  Three
 1   1    b  Three
 3   1    d  Three,
    ID name  score
 2   2    c  Three,
    ID name  score
 4   3    e  Three,
    ID name  score
 5   5    f  Three]
 
 
>>> dataframes[0]
   ID name  score
0   1    a  Three
1   1    b  Three
3   1    d  Three

>>> dataframes[1]
   ID name  score
2   2    c  Three
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