Get First Top N Rows in a Pandas DataFrame

Kontext Kontext 0 443 0.43 index 9/4/2022

Code description

Method pandas.DataFrame.head can be used to retrieve top N records from a DataFrame object. It has one optional parameter for the number of rows to return; the default value is 5 if not specified.

Syntax

    DataFrame.head(n=5)  
    

Sample output:

          A          B
0  0.000000   0.000000
1  1.010101  10.101010
2  2.020202  20.202020
3  3.030303  30.303030
4  4.040404  40.404040
5  5.050505  50.505051
6  6.060606  60.606061
7  7.070707  70.707071
8  8.080808  80.808081
9  9.090909  90.909091

Code snippet

    import pandas as pd
    import numpy as np
    
    data = {}
    data['A'] = np.linspace(start=0, stop=100, num=100)
    data['B'] = np.linspace(start=0, stop=1000, num=100)
    df = pd.DataFrame(data)
    print(df)
    
    # Get top 10 records
    df1 = df.head(10)
    print(df1)
    
pandas python

Join the Discussion

View or add your thoughts below

Comments