0

I was wondering if you could help me with my problem. I have this main Data Frame :

df = pd.DataFrame({"Ind" : list(range(1,10)), "Price" : np.random.rand(9), "Year" : [2018,2018,2018,2018,2019,2019,2019,2019,2019]})

And I would to create 2 Data Frames based on the year The basic solution is to create 2 Data Frames separately :

df_2018 = df.loc[df.Year == 2018]
df_2019 = df.loc[df.Year == 2019]

My main goal is to try to assign the year directly to the name of the new Data Frame, I would like to do something like this :

i = "2018"
df_i = df.loc[df.Year == i]

Is there any solution ?

I really appreciate your help

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Ash
  • 79
  • 1
  • 4
  • 2
    IMO, your life will be much easier if you use a dict to store them. This is as concise as `dict(tuple(df.groupby('Year')))` – ALollz Oct 25 '19 at 16:16
  • I would like to store them as DataFrames. – Ash Oct 25 '19 at 16:19
  • 1
    They would still be data frames. But in a dictionary. That means if you do `d = dict(tuple(df.groupby('Year')))`, then you can access them by doing `d[2018]` or `d[2019]`. – rafaelc Oct 25 '19 at 16:20
  • My main goal is to keep them as data frames and assign the names automatically with the given year. I would like to have : df_2018 df_2019 But automatically – Ash Oct 25 '19 at 16:23
  • That's doable, but awful. Not recommended at all. Better to have one dictionary and access by keys (i.e. `d[2018]`) than to have a thousand variables and access themdirectly (i.e. `d_2018`), There is literally no gain in having a thousand variables, and the difference between `d_2018 and d[2018]` is just one character more – rafaelc Oct 25 '19 at 16:26
  • @Hakimachraf but why? whats the difference between df_2018 and d[2018]? – Chris Doyle Oct 25 '19 at 16:26
  • a blog about why you dont want to do the approach you are trying.....http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html – Chris Doyle Oct 25 '19 at 16:32
  • @Hakimachraf this is a very common question. I'll mark this as a duplicate of [this](https://stackoverflow.com/q/1373164/2336654) in a moment – piRSquared Oct 25 '19 at 16:58

0 Answers0