split a Pandas series without a multiindex

前端 未结 2 1470
时光取名叫无心
时光取名叫无心 2021-01-07 03:39

I would like to take a Pandas Series with a single-level index and split on that index into a dataframe with multiple columns. For instance, for input:

s = p         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 04:25

    You can use groupby, apply, reset_index to create a multiindex Series, and then call unstack:

    import pandas as pd
    s = pd.Series(range(10,17), index=['a','a','b','b','c','c','c'])
    df = s.groupby(level=0).apply(pd.Series.reset_index, drop=True).unstack(0)
    print df
    

    output:

       a   b   c
    0  10  12  14
    1  11  13  15
    2 NaN NaN  16
    

提交回复
热议问题