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