Pandas dataframe stores values as rows and columns.
You can get the first row of a column in the pandas dataframe using df.loc[0, ‘Column Name’] statement.
Basic Example
- Use the
loc
attribute with a row axis value of0
to get the first row of a column in the pandas dataframe.
df.loc[0, 'Column Name']
- The first-row value of the column printed.
This tutorial teaches you how to get the first row of a column in the Pandas Dataframe.
Table of Contents
Sample Dataframe
For demonstration, first, create a dataframe with three columns.
import pandas as pd
import numpy as np
data = {'Column 1': [1,2,np.nan,4,5,np.nan,None],
'Column 2': [2,2,np.nan,4,np.nan,np.nan,None],
'Column 3': [3,2,None,4,5,None,None]
}
df = pd.DataFrame(data,columns=['Column 1','Column 2','Column 3'])
df
Dataframe Will Look Like
Column 1 | Column 2 | Column 3 | |
---|---|---|---|
0 | 1.0 | 2.0 | 3.0 |
1 | 2.0 | 2.0 | 2.0 |
2 | NaN | NaN | NaN |
3 | 4.0 | 4.0 | 4.0 |
4 | 5.0 | NaN | 5.0 |
5 | NaN | NaN | NaN |
6 | NaN | NaN | NaN |
Now, you’ll use this dataframe and select the first row of any given column.
Using loc attribute
The loc
selects rows based on their label(s).
- Pass only the row and column labels to get any cell value of a pandas dataframe.
- The first row’s index will be
0
if you’ve NOT used any custom row index - If you’ve used any custom index, use that index name as the first parameter and the column name as the second parameter to get the first row of any column
Get the index of the First row
df.index[0]
Output
0
Now use this index and the column name to select the first row of the specific column.
Code
The following code demonstrates how to select the first row of the column with the name Column 1.
df.loc[0, 'Column 1']
Output
1.0
Using iloc attribute
The iloc
selects rows based on Integers.
- Pass only the row and column index to select any cell value of a pandas dataframe.
The first row’s index will be 0
.
- Use the
0
in the row index and the appropriate column index in theiloc
attribute.
Code
df.iloc[0, 0]
You’ll see the below output. The first row of the first column is printed.
Output
1.0
Using Head() Method
The head()
method prints the first n
rows of the dataframe.
To print only the first row of a specific column,
- Select the subset of that column using
df[[column name]]
- Use the
head(1)
to print the value
Code
df[['Column 1']].head(1)
Output
Column 1 | |
---|---|
0 | 1.0 |