Indexes are position numbers of each element in python. Indexes start from zero. These numbers helps to pick values from a given position in a data frame.
Hence, the first element in a data in python will have index=0, the second element will have index=1 so on and so forth.
Indexes in 1D objects
One dimensional(1D) objects can be imagined as a single column. Which have many rows and just one column. For such kind of data if you need to extract a portion of data, then you can specify which values you need using index numbers.
In below example, a 1D list is sliced using different indexing options
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Creating a simple list SimpleNumericList=[10,20,30,40] print(SimpleNumericList) # Accessing first element using index print(SimpleNumericList[0]) # Accessing second element print(SimpleNumericList[1]) # Accessing first two elements # Note that last element in Python range is excluded print(SimpleNumericList[0:2]) # Get all elements after index 2 print(SimpleNumericList[2:]) # Get all elements before index 2 print(SimpleNumericList[:2]) # Accessing last element using negative indexing # Note that negative indexes start from -1 print(SimpleNumericList[-1]) |
Sample Output:


Indexes in 2D objects
When you are trying to slice and get a portion of data from a Two dimensional object like a DataFrame, then you need to provide two set of indexes, one for Rows and one for columns. It’s like which rows you need and which columns you need from the data.
Defining a sample data frame below to illustrate the indexing examples
1 2 3 4 5 6 7 8 9 |
# Defining sample Employee Data import pandas as pd EmployeeData=pd.DataFrame({'Name': ['ram','ravi','sham','sita','gita'], 'id': [101,102,103,104,105], 'Gender': ['M','M','M','F','F'], 'Age': [21,25,24,28,25] }) # Printing data EmployeeData |
Sample Output:

In the below examples, you can see how to subset a DataFrame by providing the indexes of rows and columns.
1 2 3 4 5 6 7 8 9 10 11 12 |
# Accessing Data via indexing property iloc (index Location in ROWS, COLS) # We are accessing 2nd Row and 2nd Column print(EmployeeData.iloc[1,1]) # Accessing first 5 values of First Column print(EmployeeData.iloc[0:5,0]) # Accessing first 5 values of First 2 Columns print(EmployeeData.iloc[0:5,0:2]) # Accessing specific values of list of rows and columns print(EmployeeData.iloc[[0,3,4],[1,3]]) |
Sample Output:

