Thursday 21 September 2023

How to Get the First N Rows of a Pandas DataFrame

Dataframe head method return first n rows.

 

Example

df.head(2)

 

Above snippet return first two rows of the dataframe.

 

df.head()

If you do not pass any argument to the head() method, it print 5 rows by default.

 

head() method support negative values

For negative values of `n`, this function returns all rows except the last `|n|` rows, equivalent to ``df[:n]``.

 

Example

total_rows = len(df)
total_rows_minus_three = total_rows-3
first_three_rows = df.head(-total_rows_minus_three)

 

‘df.head(-total_rows_minus_three)’ statement return first 3 rows of the dataframe (assume total rows are > 3).

 

Find the below working application.

first_n_rows.py
# Import the pandas Library.
import pandas as pd

# Specify the file path to the CSV file relative to the project directory.
file_path = '../../data/csv/ipl_matches.csv'

# Set options to display all columns and increase the maximum width to print the columns in same row
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)

# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)

first_five_rows = df.head()
print("First five rows\n", first_five_rows)

first_two_rows = df.head(2)
print("\nFirst two rows\n", first_two_rows)

# Get the total number of rows using the len() function
total_rows = len(df)
total_rows_minus_three = total_rows-3
first_three_rows = df.head(-total_rows_minus_three)
print("\nFirst three rows\n", first_three_rows)

 

Output

First five rows
        id        city        date player_of_match                                       venue  neutral_venue                        team1                        team2                  toss_winner toss_decision                       winner   result  result_margin eliminator method    umpire1         umpire2
0  335982   Bangalore  2008-04-18     BB McCullum                       M Chinnaswamy Stadium              0  Royal Challengers Bangalore        Kolkata Knight Riders  Royal Challengers Bangalore         field        Kolkata Knight Riders     runs          140.0          N    NaN  Asad Rauf     RE Koertzen
1  335983  Chandigarh  2008-04-19      MEK Hussey  Punjab Cricket Association Stadium, Mohali              0              Kings XI Punjab          Chennai Super Kings          Chennai Super Kings           bat          Chennai Super Kings     runs           33.0          N    NaN  MR Benson      SL Shastri
2  335984       Delhi  2008-04-19     MF Maharoof                            Feroz Shah Kotla              0             Delhi Daredevils             Rajasthan Royals             Rajasthan Royals           bat             Delhi Daredevils  wickets            9.0          N    NaN  Aleem Dar  GA Pratapkumar
3  335985      Mumbai  2008-04-20      MV Boucher                            Wankhede Stadium              0               Mumbai Indians  Royal Challengers Bangalore               Mumbai Indians           bat  Royal Challengers Bangalore  wickets            5.0          N    NaN   SJ Davis       DJ Harper
4  335986     Kolkata  2008-04-20       DJ Hussey                                Eden Gardens              0        Kolkata Knight Riders              Deccan Chargers              Deccan Chargers           bat        Kolkata Knight Riders  wickets            5.0          N    NaN  BF Bowden     K Hariharan

First two rows
        id        city        date player_of_match                                       venue  neutral_venue                        team1                  team2                  toss_winner toss_decision                 winner result  result_margin eliminator method    umpire1      umpire2
0  335982   Bangalore  2008-04-18     BB McCullum                       M Chinnaswamy Stadium              0  Royal Challengers Bangalore  Kolkata Knight Riders  Royal Challengers Bangalore         field  Kolkata Knight Riders   runs          140.0          N    NaN  Asad Rauf  RE Koertzen
1  335983  Chandigarh  2008-04-19      MEK Hussey  Punjab Cricket Association Stadium, Mohali              0              Kings XI Punjab    Chennai Super Kings          Chennai Super Kings           bat    Chennai Super Kings   runs           33.0          N    NaN  MR Benson   SL Shastri

First three rows
        id        city        date player_of_match                                       venue  neutral_venue                        team1                  team2                  toss_winner toss_decision                 winner   result  result_margin eliminator method    umpire1         umpire2
0  335982   Bangalore  2008-04-18     BB McCullum                       M Chinnaswamy Stadium              0  Royal Challengers Bangalore  Kolkata Knight Riders  Royal Challengers Bangalore         field  Kolkata Knight Riders     runs          140.0          N    NaN  Asad Rauf     RE Koertzen
1  335983  Chandigarh  2008-04-19      MEK Hussey  Punjab Cricket Association Stadium, Mohali              0              Kings XI Punjab    Chennai Super Kings          Chennai Super Kings           bat    Chennai Super Kings     runs           33.0          N    NaN  MR Benson      SL Shastri
2  335984       Delhi  2008-04-19     MF Maharoof                            Feroz Shah Kotla              0             Delhi Daredevils       Rajasthan Royals             Rajasthan Royals           bat       Delhi Daredevils  wickets            9.0          N    NaN  Aleem Dar  GA Pratapkumar

 

 


Previous                                                 Next                                                 Home

No comments:

Post a Comment