Group by consecutive index numbers

前端 未结 6 2072
忘掉有多难
忘掉有多难 2021-01-03 19:00

I was wondering if there is a way to groupby consecutive index numbers and move the groups in different columns. Here is an example of the DataFrame I\'m using:



        
6条回答
  •  甜味超标
    2021-01-03 19:36

    Create a new pandas.Series with a new pandas.MultiIndex

    a = pd.factorize(df.index - np.arange(len(df)))[0]
    b = df.groupby(a).cumcount()
    
    pd.Series(df['0'].to_numpy(), [b, a]).unstack()
    
                  0             1
    0  19218.965703  19279.216956
    1  19247.621650  19330.087371
    2  19232.651322  19304.316973
    

    Similar but with more Numpy

    a = pd.factorize(df.index - np.arange(len(df)))[0]
    b = df.groupby(a).cumcount()
    
    c = np.empty((b.max() + 1, a.max() + 1), float)
    c.fill(np.nan)
    c[b, a] = np.ravel(df)
    pd.DataFrame(c)
    
                  0             1
    0  19218.965703  19279.216956
    1  19247.621650  19330.087371
    2  19232.651322  19304.316973
    

提交回复
热议问题