How do I create dynamic variable names inside a loop in pandas

后端 未结 2 519
醉梦人生
醉梦人生 2020-12-17 04:04

I have a dataframe like

month  dest
1       a
1       bb
2       cc 
2       dd
3       ee
4       bb

I need to create a set to 4 another d

相关标签:
2条回答
  • 2020-12-17 05:01

    You can use a list of dataframes:

    dataframe = []
    dataframe.append(None)
    
    group = org_dataframe.groupby('month')
    
    for n,g in group:
        dataframe.append(g)
    
    dataframe[1]
    

    Output:

       month dest
    0      1    a
    1      1   bb
    
    dataframe[2]
    

    Output:

       month dest
    2      2   cc
    3      2   dd
    
    0 讨论(0)
  • 2020-12-17 05:03

    I think the best is create dict of objects - see How do I create a variable number of variables?

    You can use dict of DataFrames by converting groupby object to dict:

    d = dict(tuple(df.groupby('month')))
    print (d)
    {1:    month dest
    0      1    a
    1      1   bb, 2:    month dest
    2      2   cc
    3      2   dd, 3:    month dest
    4      3   ee, 4:    month dest
    5      4   bb}
    
    print (d[1])
       month dest
    0      1    a
    1      1   bb
    

    Another solution:

    for i, x in df.groupby('month'):
        globals()['dataframe' + str(i)] = x
    
    print (dataframe1)
       month dest
    0      1    a
    1      1   bb
    
    0 讨论(0)
提交回复
热议问题