1

Want to find an easier way to subset dataframe and creating those as new dataframes

A011 = DF[DF['id']=="A011"]
A012 = DF[DF['id']=="A012"]
A013 = DF[DF['id']=="A013"]
A014 = DF[DF['id']=="A014"]

This works but inefficient. I actually have 162 unique values.

DF = pd.DataFrame({'id': ["A011", "A012", "A012", "A012","A011", "A012", "A012", "A012"],\
'value': [1, 2, 3, 4, 1, 2, 3, 4]})
A011 = DF[DF['id']=="A011"]
A012 = DF[DF['id']=="A012"]
A013 = DF[DF['id']=="A013"]
A014 = DF[DF['id']=="A014"]

Desired output

    id  value
0   A011    1
4   A011    1

    id  value
1   A012    2
5   A012    2
YilGuk Seo
  • 77
  • 6

1 Answers1

0
df = pd.DataFrame({'id': ["A011", "A012", "A012", 
"A012","A011", "A012", "A012", "A012"], 'value': [1, 2, 3, 4, 1, 2, 3, 4]})    
result = [x.reset_index(drop=True) for _, x in df.groupby(['id'])]

Since you want to create dataframes based on the unique id column, we can group the dataframe by the id column which returns a dataframe for each group. Use reset_index on the created dataframe to drop the original index.

mujjiga
  • 16,186
  • 2
  • 33
  • 51