• Post author:
  • Post category:Pandas
  • Post last modified:May 6, 2024
  • Reading time:16 mins read
You are currently viewing Get First Row of Pandas DataFrame?

By using DataFrame.iloc[0] and head(1) you can select/get the first row of pandas DataFrame.iloc[] is a property that is used to select rows and columns by position/index. If the position/index does not exist, it gives an index error.

Advertisements

In this article, I will cover usage of pandas.DataFrame.iloc[] and using this how we can get the first row of Pandas DataFrame in different ways with examples.

Key Points –

  • The first row of a Pandas DataFrame can be accessed using methods like .iloc[0] or .head(1).
  • Both methods retrieve the first row, with .iloc[0] directly accessing it by index position and .head(1) providing a convenient way to display it.
  • When using .iloc[0], ensure that the DataFrame has at least one row; otherwise, it will raise an IndexError.
  • .head(1) returns the first row as well, providing a convenient way to display or inspect it.

Quick Examples of the First Row of DataFrame

If you are in a hurry, below are some quick examples of how to get the first row of DataFrame.


# Quick examples of get first row of pandas dataframe
 
# Example 1: Get first Row of Pandas DataFrame
print(df.iloc[0])

# Example 2: Get first row using range index
print(df.iloc[:1])

# Example 3: Get first row value 
# Using particular column
print(df['Fee'].iloc[0])

# Example 4:  Get first row value
# Using index range
print(df['Discount'].iloc[:1])

# Example 5: Get first row using index
print(df.loc[df.index[0]])

# Example 6:  Get first row
# Using values[]
print(df.values[:1])

# Example 7: Get first row of particular column
print(df['Fee'].values[:1])

# Example 8: Get the first row use head()
print(df.head(1))

# Example 9: Get the first row of DataFrame as a list
print(df.iloc[0].tolist())

To run some examples of getting the first row of pandas’ DataFrame, let’s create DataFrame dictionary.


# Import pandas library
# Create pandas DataFrame
import pandas as pd
technologies = {
    'Courses':["Spark","PySpark","Hadoop","Python","pandas"],
    'Fee' :[20000,25000,26000,22000,24000],
    'Duration':['30days','40days','35days','40days','60days'],
    'Discount':[1000,2300,1200,2500,2000]
              }
index_labels=['r1','r2','r3','r4','r5']
df = pd.DataFrame(technologies, columns = ['Courses', 'Fee', 'Duration', 'Discount'], index = index_labels)
print("Create DataFrame:\n", df)

Yields below output.

pandas get first row

Get the First Row of Pandas using iloc[]

Using the Pandas iloc[] attribute we can get a single row or column by using an index, by specifying the index position 0 we can get the first row of DataFrame.iloc[0] will return the first row of DataFrame in the form of Pandas Series.

Related: You can use df.iloc[] to get the last row of DataFrame.


# Get first row using row position
print(df.iloc[0])

Yields below output.

pandas get first row

df.iloc[:1] selects the rows from index 0 up to (but not including) index 1, effectively retrieving the first row of the DataFrame. This approach is another valid way to obtain the first row using integer-based indexing with .iloc[].


# Get first row 
# Using range index
print(df.iloc[:1])

# Output:
#  Courses    Fee Duration  Discount
#  r1   Spark  20000   30days      1000

Get the First Row using loc()

We can also get the first row of DataFrame using the loc[] attribute for that, we have to pass the first row index with the help of the index[] attribute. It will return the first row in the form of Series object.


# Get first row using loc() function
first_row = df.loc[df.index[0]]
print(first_row)

# Output:
# Courses     Spark
# Fee         20000
# Duration    30days
# Discount     1000
# Name: r1, dtype: object

In the above example, uses df.index[0] to get the label of the first row in the index and then uses loc to select the corresponding row based on the label. The result, stored in the variable first_row, will be a Pandas Series containing the values of the first row.

Using values() Attribute 

The values attribute of a Pandas DataFrame returns a NumPy representation of the DataFrame. Leveraging this attribute, we can extract the first row of the DataFrame in the form of a NumPy array.


# Get first row using loc() function
print(df.values[:1])

# Output:
# [['Spark' 20000 '30day' 1000]]

# Get particular column
print(df['Fee'].values[:1])

# Output:
# [20000]

Get the First Row of DataFrame using head()

The pandas.DataFrame.head() method returns the first n rows of DataFrame. We can use this head() function to get only the first row of the DataFrame, for that, we pass '1' as an argument to this function. It will return the first row of DataFrame.


# Get the first row use head()
print(df.head(1))

# Output:
#    Courses    Fee Duration  Discount
# r1   Spark  20000    30day      1000

Get the First Row of Pandas as a List

As we know from the above, we have got the first row of the DataFrame using df.iloc[0]. It has given the result as a series object. Using the series.tolist() function, we can get the first row of DataFrame in the form of a list. For example,


# Get the first row of DataFrame as a list
print(df.iloc[0].tolist())

# Output:
# ['Spark', 20000, '30day', 1000]

Get the First Row of a particular column

If we want to get the value of the first row based on a particular column, we can pass the specified column into DataFrame and then call iloc[] attribute. It will return value of first row based on specified column.


# Get first row value using particular column
print(df['Fee'].iloc[0])

# Output:
# 20000

Alternatively, we can get the value of the first row based on a particular column using the index range of the iloc[] attribute. It will return the first-row value in the form of a Series.


#  Get first row value using index range
print(df['Discount'].iloc[:1])

# Output:
# r1    1000
# Name: Discount, dtype: int64

Frequently Asked Questions on Get First Row of DataFrame

How do I get the first row of a Pandas DataFrame?

To get the first row of a Pandas DataFrame, you can use either the iloc indexer or the head method.

Can I use head(1) to get the first row?

You can use the head(1) method to get the first row of a Pandas DataFrame. The head method is typically used to return the first N rows of a DataFrame, and when you specify 1 as the argument, it will return the first row as a DataFrame.

How do I extract a specific column from the first row?

To extract a specific column from the first row, you can combine iloc with column indexing. For example, to get the value in the “column_name” column of the first row.

What is the difference between iloc[0] and head(1)?

Both methods will give you the first row, but iloc[0] returns a Series, while head(1) returns a DataFrame with one row. Choose based on your preference and use case.

Can I use loc instead of iloc to get the first row?

You can use the loc indexer instead of iloc to get the first row of a Pandas DataFrame, especially if your DataFrame has a labeled index.

How can I get the first N rows of a DataFrame?

To get the first N rows of a Pandas DataFrame, you can use the head() method. Replace N with the number of rows you want to retrieve. For instance, if you want to get the first 5 rows.

Conclusion

In this article, I have explained DataFrame.iloc[] and used this first row of DataFrame in different ways. As well as I explained how to get the first row of DataFrame using head() and other functions.

Happy Learning !!

References