Skip to content
Related Articles

Related Articles

How to get rows/index names in Pandas dataframe
  • Last Updated : 05 Dec, 2018
GeeksforGeeks - Summer Carnival Banner

While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names in order to perform some certain operations.

Let’s discuss how to get row names in Pandas dataframe.

First, let’s create a simple dataframe with nba.csv




# Import pandas package 
import pandas as pd 
    
# making data frame 
    
# calling head() method  
# storing in new variable 
data_top = data.head(10
    
# display 
data_top 

Now let’s try to get the row name from above dataset.



Method #1: Simply iterate over indices




# Import pandas package 
import pandas as pd 
    
# making data frame 
data = pd.read_csv("nba.csv"
  
# calling head() method  
# storing in new variable 
data_top = data.head() 
    
# iterating the columns
for row in data_top.index:
    print(row, end = " ")

Output:

0 1 2 3 4 5 6 7 8 9 

 
Method #2: Using rows with dataframe object




# Import pandas package 
import pandas as pd 
    
# making data frame 
data = pd.read_csv("nba.csv"
  
# calling head() method  
# storing in new variable 
data_top = data.head() 
    
# list(data_top) or
list(data_top.index)

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 
Method #3: index.values method returns an array of index.




# Import pandas package 
import pandas as pd 
    
# making data frame 
data = pd.read_csv("nba.csv"
  
# calling head() method  
# storing in new variable 
data_top = data.head() 
    
list(data_top.index.values)

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 
Method #4: Using tolist() method with values with given the list of index.




# Import pandas package 
import pandas as pd 
    
# making data frame 
data = pd.read_csv("nba.csv"
  
# calling head() method  
# storing in new variable 
data_top = data.head() 
    
list(data_top.index.values.tolist())

Output:



[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 
Method #5: Count number of rows in dataframe

Since we have loaded only 10 top rows of dataframe using head() method, let’s varify total number of rows first.




# iterate the indices and print each one
for row in data.index:
    print(row, end= " ")

Output:

Now, let’s print the total count of index.




# Import pandas package 
import pandas as pd 
    
# making data frame 
data = pd.read_csv("nba.csv"
  
row_count = 0
  
# iterating over indices
for col in data.index:
    row_count += 1
  
# print the row count
print(row_count)

Output:

458

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :