30 Dec Indexing in Pandas
In this lesson, we will learn how Indexing works in Pandas. We can easily index and select data in Pandas. Before moving further, we’ve prepared a video tutorial to understand indexing in Pandas:
Let’s say we have the following CSV file Students.csv:
Indexing
Indexing means selecting specific rows and columns of data from DataFrame. A DataFrame includes columns, index, and data. Let us see some examples:
- Indexing in Pandas using the indexing operator
- Indexing in Pandas using loc[]
- Indexing in Pandas using iloc[]
Indexing in Pandas using the indexing operator
We can directly use the [] i.e. the indexing operator in Pandas to retrieve records. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import pandas as pd # Input CSV file # Loading CSV in the DataFrame df = pd.read_csv('Students.csv',index_col ="Student") # Display the CSV file records print("Our DataFrame =\n", df) # Use the indexing operator res = df["Marks"] # Retrieving marks of students print("\n",res) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Our DataFrame = Student Rank Marks Amit 1 95 Virat 2 90 David 3 80 Will 4 75 Steve 5 65 Student Amit 95 Virat 90 David 80 Will 75 Steve 65 |
Indexing in Pandas using loc[]
To retrieve a single row in Pandas, use the loc[] in Pandas. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import pandas as pd # Input CSV file # Loading CSV in the DataFrame df = pd.read_csv('Students.csv',index_col ="Student") # Display the CSV file records print("Our DataFrame =\n", df) # Retrieving a single row with Name Amit print("\n",df.loc["Amit"]) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Our DataFrame Student Rank Marks Amit 1 95 Virat 2 90 David 3 80 Will 4 75 Steve 5 65 Rank 1 Marks 95 Student: Amit, dtype:object |
Indexing in Pandas using iloc[]
To retrieve the rows and columns by position, use the iloc[] in Pandas. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import pandas as pd # Input CSV file # Loading CSV in the DataFrame df = pd.read_csv('Students.csv',index_col ="Student") # Display the CSV file records print("Our DataFrame =\n",df) # Retrieving row 3 records res = df.iloc[2] print("\n",res) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Our DataFrame = Student Rank Marks Amit 1 95 Virat 2 90 David 3 80 Will 4 75 Steve 5 65 Student David Rank 3 Marks 80 |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments