Pandas Split DataFrame using row index

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

    I think this is you are looking for.,

    l = [2, 5, 7]
    dfs=[]
    i=0
    for val in l:
        if i==0:
            temp=df.iloc[:val]
            dfs.append(temp)
        elif i==len(l):
            temp=df.iloc[val]
            dfs.append(temp)        
        else:
            temp=df.iloc[l[i-1]:val]
            dfs.append(temp)
        i+=1
    

    Output:

       a  b  c
    0  1  1  1
    1  2  2  2
       a  b  c
    2  3  3  3
    3  4  4  4
    4  5  5  5
       a  b  c
    5  6  6  6
    6  7  7  7
    

    Another Solution:

    l = [2, 5, 7]
    t= np.arange(l[-1])
    l.reverse()
    for val in l:
        t[:val]=val
    temp=pd.DataFrame(t)
    temp=pd.concat([df,temp],axis=1)
    for u,v in temp.groupby(0):
        print v
    

    Output:

       a  b  c  0
    0  1  1  1  2
    1  2  2  2  2
       a  b  c  0
    2  3  3  3  5
    3  4  4  4  5
    4  5  5  5  5
       a  b  c  0
    5  6  6  6  7
    6  7  7  7  7
    

提交回复
热议问题