python pandas select both head and tail python pandas select both head and tail python python

python pandas select both head and tail


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  C2012-11-29  0  0  02012-11-30  1  1  12012-12-07  8  8  82012-12-08  9  9  9

df = df.iloc[np.r_[0:4, -4:0]]print (df)            A  B  C2012-11-29  0  0  02012-11-30  1  1  12012-12-01  2  2  22012-12-02  3  3  32012-12-05  6  6  62012-12-06  7  7  72012-12-07  8  8  82012-12-08  9  9  9


You can use df.head(5) and df.tail(5) to get first five and last five.Optionally you can create new data frame and append() head and tail:

new_df = df.tail(5)new_df = new_df.append(df.head(5))


Not quite the same question but if you just want to show the top / bottom 5 rows (eg with display in jupyter or regular print, there's potentially a simpler way than this if you use the pd.option_context context.

#make 100 3d random numbersdf = pd.DataFrame(np.random.randn(100,3))# sort them by their axis sumdf = df.loc[df.sum(axis=1).index]with pd.option_context('display.max_rows',10):    print(df)

Outputs:

           0         1         20  -0.649105 -0.413335  0.3748721   3.390490  0.552708 -1.7238642  -0.781308 -0.277342 -0.9031273   0.433665 -1.125215 -0.2902284  -2.028750 -0.083870 -0.094274..       ...       ...       ...95  0.443618 -1.473138  1.13216196 -1.370215 -0.196425 -0.52840197  1.062717 -0.997204 -1.66695398  1.303512  0.699318 -0.86357799 -0.109340 -1.330882 -1.455040[100 rows x 3 columns]