pythonpandasslicetailhead

python pandas select both head and tail


For a DataFrame in Pandas, how can I select both the first 5 values and last 5 values?

For example

In [11]: df
Out[11]: 
        A  B  C
2012-11-29  0  0  0
2012-11-30  1  1  1
2012-12-01  2  2  2
2012-12-02  3  3  3
2012-12-03  4  4  4
2012-12-04  5  5  5
2012-12-05  6  6  6
2012-12-06  7  7  7
2012-12-07  8  8  8
2012-12-08  9  9  9

How to show the first two and the last two rows?


Solution

  • You can use iloc with numpy.r_:

    print (np.r_[0:2, -2:0])
    [ 0  1 -2 -1]
    
    df = df.iloc[np.r_[0:2, -2:0]]
    print (df)
                A  B  C
    2012-11-29  0  0  0
    2012-11-30  1  1  1
    2012-12-07  8  8  8
    2012-12-08  9  9  9
    

    df = df.iloc[np.r_[0:4, -4:0]]
    print (df)
                A  B  C
    2012-11-29  0  0  0
    2012-11-30  1  1  1
    2012-12-01  2  2  2
    2012-12-02  3  3  3
    2012-12-05  6  6  6
    2012-12-06  7  7  7
    2012-12-07  8  8  8
    2012-12-08  9  9  9