Pandas Series of lists to one series

后端 未结 9 2209
野性不改
野性不改 2020-12-28 13:18

I have a Pandas Series of lists of strings:

0                           [slim, waist, man]
1                                [slim, waistline]
2                       


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-28 13:36

    Here's a simple method using only pandas functions:

    import pandas as pd
    
    s = pd.Series([
        ['slim', 'waist', 'man'],
        ['slim', 'waistline'],
        ['santa']])
    

    Then

    s.apply(pd.Series).stack().reset_index(drop=True)
    

    gives the desired output. In some cases you might want to save the original index and add a second level to index the nested elements, e.g.

    0  0         slim
       1        waist
       2          man
    1  0         slim
       1    waistline
    2  0        santa
    

    If this is what you want, just omit .reset_index(drop=True) from the chain.

提交回复
热议问题