Python Pandas Dynamically Create a Dataframe

后端 未结 1 1416
Happy的楠姐
Happy的楠姐 2020-12-18 09:45

The code below will generate the desired output in ONE dataframe, however, I would like to dynamically create data frames in a FOR loop then assign the shif

1条回答
  •  攒了一身酷
    2020-12-18 10:22

    I think the best is create dictionary of DataFrames:

    d = {}
    for i in range(12,0,-1):
        d['t' + str(i)] = df.shift(i).add_suffix('_t' + str(i))
    

    If need specify columns first:

    d = {}
    cols = ['column1','column2']
    for i in range(12,0,-1):
        d['t' + str(i)] = df[cols].shift(i).add_suffix('_t' + str(i))
    

    dict comprehension solution:

    d = {'t' + str(i): df.shift(i).add_suffix('_t' + str(i)) for i in range(12,0,-1)}
    

    print (d['t10'])
        column1_t10  column2_t10
    0           NaN          NaN
    1           NaN          NaN
    2           NaN          NaN
    3           NaN          NaN
    4           NaN          NaN
    5           NaN          NaN
    6           NaN          NaN
    7           NaN          NaN
    8           NaN          NaN
    9           NaN          NaN
    10          0.0         19.0
    11          1.0         18.0
    12          2.0         17.0
    13          3.0         16.0
    14          4.0         15.0
    15          5.0         14.0
    16          6.0         13.0
    17          7.0         12.0
    18          8.0         11.0
    19          9.0         10.0
    

    EDIT: Is it possible by globals, but much better is dictionary:

    d = {}
    cols = ['column1','column2']
    for i in range(12,0,-1):
        globals()['df' + str(i)] =  df[cols].shift(i).add_suffix('_t' + str(i))
    
    print (df10)
        column1_t10  column2_t10
    0           NaN          NaN
    1           NaN          NaN
    2           NaN          NaN
    3           NaN          NaN
    4           NaN          NaN
    5           NaN          NaN
    6           NaN          NaN
    7           NaN          NaN
    8           NaN          NaN
    9           NaN          NaN
    10          0.0         19.0
    11          1.0         18.0
    12          2.0         17.0
    13          3.0         16.0
    14          4.0         15.0
    15          5.0         14.0
    16          6.0         13.0
    17          7.0         12.0
    18          8.0         11.0
    19          9.0         10.0
    

    0 讨论(0)
提交回复
热议问题