Search code examples
pythonpandasrow

How to move the first 2 rows of a file to the end with pandas


I have a file with 2 columns and 10 rows:

01/12/2019  234.75
02/12/2019  303.6666666666667
03/12/2019  213.29166666666663
04/12/2019  187.91666666666663
05/12/2019  191.875
06/12/2019  188.25
07/12/2019  208.5833333333333
08/12/2019  184.125
09/12/2019  210.16666666666663
10/12/2019  315.4166666666667

I want to move the first 2 rows at the end of the file. How I could do that with pandas ? The file is a sample, in fact there may be many more rows.

col_names=['day','val']
df_moved = pd.read_csv(o,sep='\t',header=None,names=col_names,skiprows=[1]) #for skipping the first two rows

Solution

  • Use concat with selecting rows by positions:

    df1 = pd.concat([df.iloc[2:], df.iloc[:2]])
    

    Or DataFrame.reindex with appended index values:

    df1 = df.reindex(df.index[2:].append(df.index[:2]))
    

    Or solution with np.r_:

    df1 = df.iloc[np.r_[2:len(df), 0:2]]
    

    print (df1)
              day         val
    2  03/12/2019  213.291667
    3  04/12/2019  187.916667
    4  05/12/2019  191.875000
    5  06/12/2019  188.250000
    6  07/12/2019  208.583333
    7  08/12/2019  184.125000
    8  09/12/2019  210.166667
    9  10/12/2019  315.416667
    0  01/12/2019  234.750000
    1  02/12/2019  303.666667