split a Pandas series without a multiindex

前端 未结 2 1471
时光取名叫无心
时光取名叫无心 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
    
    0 讨论(0)
  • 2021-01-07 04:31

    Not sure how generalizable this is. I call this the groupby via concat pattern. Essentially an apply, but with control over how exactly its combined.

    In [24]: s = pd.Series(range(10,17), index=['a','a','b','b','c','c','c'])
    
    In [25]: df = DataFrame(dict(key = s.index, value = s.values))
    
    In [26]: df
    Out[26]: 
      key  value
    0   a     10
    1   a     11
    2   b     12
    3   b     13
    4   c     14
    5   c     15
    6   c     16
    
    In [27]: concat(dict([ (g,Series(grp['value'].values)) for g, grp in df.groupby('key') ]),axis=1)
    Out[27]: 
        a   b   c
    0  10  12  14
    1  11  13  15
    2 NaN NaN  16
    
    0 讨论(0)
提交回复
热议问题