Pandas expand rows from list data available in column

前端 未结 3 1965
陌清茗
陌清茗 2020-11-30 07:18

I have a data frame like this in pandas:

 column1      column2
 [a,b,c]        1
 [d,e,f]        2
 [g,h,i]        3

Expected outp

3条回答
  •  鱼传尺愫
    2020-11-30 08:04

    DataFrame.explode

    Since pandas >= 0.25.0 we have the explode method for this, which expands a list to a row for each element and repeats the rest of the columns:

    df.explode('column1').reset_index(drop=True)
    

    Output

    
      column1  column2
    0       a        1
    1       b        1
    2       c        1
    3       d        2
    4       e        2
    5       f        2
    6       g        3
    7       h        3
    8       i        3
    

    Since pandas >= 1.1.0 we have the ignore_index argument, so we don't have to chain with reset_index:

    df.explode('column1', ignore_index=True)
    

    Output

      column1  column2
    0       a        1
    1       b        1
    2       c        1
    3       d        2
    4       e        2
    5       f        2
    6       g        3
    7       h        3
    8       i        3
    

提交回复
热议问题