How to Get First Row of Pandas DataFrame (With Examples)


You can use the following syntax to get the first row of a pandas DataFrame:

df.head(1)

You can use the following syntax to get the first row of values for specific columns in a pandas DataFrame:

df[['column1', 'column2']].head(1)

And you can use the following syntax to get the first row of a pandas DataFrame based on certain criteria:

df[(df.column1 < value) & (df.column2 > value)].head(1)

The following examples show how to use this syntax in practice with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

   points  assists  rebounds
0      25        5        11
1      12        7         8
2      15        7        10
3      14        9         6
4      19       12         6
5      23        9         5
6      25        9         9
7      29        4        12

Example 1: Get First Row of Pandas DataFrame

The following code shows how to get the first row of a pandas DataFrame:

#get first row of DataFrame
df.head(1)

	points	assists	rebounds
0	25	5	11

Example 2: Get First Row of Pandas DataFrame for Specific Columns

The following code shows how to get the first column of a pandas DataFrame and return a DataFrame as a result:

#get first row of values for points and rebounds columns
df[['points', 'rebounds']].head(1)

        points	rebounds
0	25	11

Example 3: Get First Row of Pandas DataFrame Based on Criteria

The following code shows how to get the first row of a pandas DataFrame that meets certain criteria:

#get first row where points < 20 and assists > 10
df[(df.points < 20) & (df.assists > 10)].head(1)

	points	assists	rebounds
4	19	12	6

Additional Resources

How to Get First Column of Pandas DataFrame
How to Add Rows to a Pandas DataFrame
How to Count Number of Rows in Pandas DataFrame

Leave a Reply

Your email address will not be published. Required fields are marked *