pythondataframerowslicealternating

python dataframe slicing by row number


all Python experts,

I'm a Python newbie, stuck with a problem which may look very simple to you. Say I have a data frame of 100 rows, how can I split it into 5 sub-frames, each of which contains the rows of 5n+0, 5n+1, 5n+2, 5n+3 and 5n+4 respectively? For instance, the 0th, 5th, 10th up to the 95th will go to one sub-frame, 1st, 6th, 11th up to 96th will go to the 2nd sub-frame and the 4th, 9th, 14th up to 99th will go to the 5th sub-frame?

This is what I have tried:

grouped = l_df.groupby(l_df.index//5)  
a_df = grouped.get_group(1)
b_df = grouped.get_group(2)
c_df = grouped.get_group(3)
d_df = grouped.get_group(4)

But each of my group got only 5 rows. Any suggestions?

Thanks much in advance!


Solution

  • Just use iloc and slice as you would do with a list i.e. start:end:step. Example:

    df = pd.DataFrame({"A":range(100)})
    display(df.T)
    display(df.iloc[0::5].T)
    display(df.iloc[1::5].T)
    display(df.iloc[2::5].T)
    # ...
    

    res