Pandas Split DataFrame using row index

后端 未结 4 1248
日久生厌
日久生厌 2021-01-18 15:08

I want to split dataframe by uneven number of rows using row index.

The below code:

groups = df.groupby((np.arange(len(df.index))/l[1]).astype(int)         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-18 15:52

    I think this is what you need:

    df = pd.DataFrame({'a': np.arange(1, 8),
                      'b': np.arange(1, 8),
                      'c': np.arange(1, 8)})
    df.head()
        a   b   c
    0   1   1   1
    1   2   2   2
    2   3   3   3
    3   4   4   4
    4   5   5   5
    5   6   6   6
    6   7   7   7
    
    last_check = 0
    dfs = []
    for ind in [2, 5, 7]:
        dfs.append(df.loc[last_check:ind-1])
        last_check = ind
    

    Although list comprehension are much more efficient than a for loop, the last_check is necessary if you don't have a pattern in your list of indices.

    dfs[0]
    
        a   b   c
    0   1   1   1
    1   2   2   2
    
    dfs[2]
    
        a   b   c
    5   6   6   6
    6   7   7   7
    

提交回复
热议问题