Pandas Split DataFrame using row index

后端 未结 4 1352
日久生厌
日久生厌 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:40

    You could use list comprehension with a little modications your list, l, first.

    print(df)
    
       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
    7  8  8  8
    
    
    l = [2,5,7]
    l_mod = [0] + l + [max(l)+1]
    
    list_of_dfs = [df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]
    

    Output:

    list_of_dfs[0]
    
       a  b  c
    0  1  1  1
    1  2  2  2
    
    list_of_dfs[1]
    
       a  b  c
    2  3  3  3
    3  4  4  4
    4  5  5  5
    
    list_of_dfs[2]
    
       a  b  c
    5  6  6  6
    6  7  7  7
    
    list_of_dfs[3]
    
       a  b  c
    7  8  8  8
    

提交回复
热议问题