Pandas column of lists, create a row for each list element

前端 未结 10 872
有刺的猬
有刺的猬 2020-11-22 06:59

I have a dataframe where some cells contain lists of multiple values. Rather than storing multiple values in a cell, I\'d like to expand the dataframe so that each item in t

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 07:32

    you can also use pd.concat and pd.melt for this:

    >>> objs = [df, pd.DataFrame(df['samples'].tolist())]
    >>> pd.concat(objs, axis=1).drop('samples', axis=1)
       subject  trial_num     0     1     2
    0        1          1 -0.49 -1.00  0.44
    1        1          2 -0.28  1.48  2.01
    2        1          3 -0.52 -1.84  0.02
    3        2          1  1.23 -1.36 -1.06
    4        2          2  0.54  0.18  0.51
    5        2          3 -2.18 -0.13 -1.35
    >>> pd.melt(_, var_name='sample_num', value_name='sample', 
    ...         value_vars=[0, 1, 2], id_vars=['subject', 'trial_num'])
        subject  trial_num sample_num  sample
    0         1          1          0   -0.49
    1         1          2          0   -0.28
    2         1          3          0   -0.52
    3         2          1          0    1.23
    4         2          2          0    0.54
    5         2          3          0   -2.18
    6         1          1          1   -1.00
    7         1          2          1    1.48
    8         1          3          1   -1.84
    9         2          1          1   -1.36
    10        2          2          1    0.18
    11        2          3          1   -0.13
    12        1          1          2    0.44
    13        1          2          2    2.01
    14        1          3          2    0.02
    15        2          1          2   -1.06
    16        2          2          2    0.51
    17        2          3          2   -1.35
    

    last, if you need you can sort base on the first the first three columns.

提交回复
热议问题