How to call pandas dataframes in a loop their key in python?

I would like to create data frames in a loop, but name each data frame with a key so as not to overwrite each data file in a loop.

Here is a simplified version of my frame frame:

ID  Field  Value
1     A     1.1
2     A     1.2
3     A     2.4
4     B     1.7
5     B     4.3
6     C     2.2

So, in this case, I would like to get 3 frames of data with the names A, B and C so this is what I'm tired of:

df2= df.groupby(['Field'])
for key, group in df2:
   key = group.reset_index()

But, of course, the name "key" is overwritten by each complex cycle. How can I call each data frame in a loop its key?

I would like to create a list of created data frames to track them.

+4
source share
2 answers

You want to save your objects in a dict file:

df_dict = {}
for key, group in df2:
   df_dict[key] = group.reset_index()
+8
source

Using a dictionary understanding, a more concise solution is as follows:

df_new = {field: df.loc[df.Field == field, :] for field in df.Field.unique()}
+2
source

Source: https://habr.com/ru/post/1598790/


All Articles