How to explode a list inside a Dataframe cell into separate rows

后端 未结 11 2347
天命终不由人
天命终不由人 2020-11-22 10:20

I\'m looking to turn a pandas cell containing a list into rows for each of those values.

So, take this:

If I\'d like to unpack and stack the value

11条回答
  •  礼貌的吻别
    2020-11-22 11:21

    So all of these answers are good but I wanted something ^really simple^ so here's my contribution:

    def explode(series):
        return pd.Series([x for _list in series for x in _list])                               
    

    That's it.. just use this when you want a new series where the lists are 'exploded'. Here's an example where we do value_counts() on taco choices :)

    In [1]: my_df = pd.DataFrame(pd.Series([['a','b','c'],['b','c'],['c']]), columns=['tacos'])      
    In [2]: my_df.head()                                                                               
    Out[2]: 
       tacos
    0  [a, b, c]
    1     [b, c]
    2        [c]
    
    In [3]: explode(my_df['tacos']).value_counts()                                                     
    Out[3]: 
    c    3
    b    2
    a    1
    

提交回复
热议问题