0

im trying to t to create 4 dataframes with an unique id. For example df1, df2,...,df4. And each one should contain data from a main dataframe.

For example, the main df looks like this

   id        subid        a
1  1         1            2 
2  1         1            10 
3  1         1            20
4  1         2            30
5  1         2            35 
6  1         2            36 
7  1         3           40
8  2         3            20
9  2         4           49
10 2         4            30

And i want a new df for each subid containing the value from column id and a. So far this is what i have

for i in range(4):
    df'i' = maindf[maindf.subid == i]

therefore df4 should look like this

id a
2 49
2 30
neto333
  • 81
  • 6
  • see this answer https://stackoverflow.com/a/51405971/14289892 – Anurag Dabas Jul 29 '21 at 16:30
  • 1
    `dfs = dict(tuple(df.groupby('subid')))` would be my suggestion. Individual groups accessed by `dfs[1]`, `dfs[2]`, `dfs[3]`, and `dfs[4]`. – Henry Ecker Jul 29 '21 at 16:34
  • Hi @HenryEcker that only makes 1 df with the first subid, but i want one df for each subid. – neto333 Jul 29 '21 at 16:39
  • No that makes a dictionary of DataFrames subdivided (keyed) by 'subid' value. – Henry Ecker Jul 29 '21 at 16:40
  • @AnuragDabas invalid syntax – neto333 Jul 29 '21 at 16:55
  • @HenryEcker orry for my dumb questions, but why when i open de dictionary i can only see the data corresponding to the subid==1. How can i see the other 3 df? – neto333 Jul 29 '21 at 16:55
  • As stated above. The 4 keys in the show sample dataframe would be `dfs[1]`, `dfs[2]`, `dfs[3]`, and `dfs[4]`. You could check `dfs.keys()` or `dfs.values()` or just `print(dfs)` to see what you have. – Henry Ecker Jul 29 '21 at 17:00

0 Answers0