The Wayback Machine - https://web.archive.org/web/20241003001001/https://www.geeksforgeeks.org/python-pandas-extracting-rows-using-loc/
Open In App

Python | Pandas Extracting rows using .loc[]

Last Updated : 30 Sep, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas provide a unique method to retrieve rows from a Data frame. DataFrame.loc[] method is a method that takes only index labels and returns row or dataframe if the index label exists in the caller data frame.

Syntax: pandas.DataFrame.loc[]

Parameters:
Index label: String or list of string of index label of rows

Return type: Data frame or Series depending on parameters

To download the CSV used in code, click here.

Example #1: Extracting single Row

In this example, Name column is made as the index column and then two single rows are extracted one by one in the form of series using index label of rows.




# importing pandas package
import pandas as pd
  
# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")
  
# retrieving row by loc method
first = data.loc["Avery Bradley"]
second = data.loc["R.J. Hunter"]
  
  
print(first, "\n\n\n", second)


Output:
As shown in the output image, two series were returned since there was only one parameter both of the times.

 
Example #2: Multiple parameters

In this example, Name column is made as the index column and then two single rows are extracted at the same time by passing a list as parameter.




# importing pandas package
import pandas as pd
  
# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")
  
# retrieving rows by loc method
rows = data.loc[["Avery Bradley", "R.J. Hunter"]]
  
# checking data type of rows
print(type(rows))
  
# display
rows


Output:
As shown in the output image, this time the data type of returned value is a data frame. Both of the rows were extracted and displayed like a new data frame.

 

Example #3: Extracting multiple rows with same index

In this example, Team name is made as the index column and one team name is passed to .loc method to check if all values with same team name have been returned or not.




# importing pandas package
import pandas as pd
  
# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Team")
  
# retrieving rows by loc method
rows = data.loc["Utah Jazz"]
  
# checking data type of rows
print(type(rows))
  
# display
rows


Output:
As shown in the output image, All rows with team name “Utah Jazz” were returned in the form of a data frame.

 

Example #4: Extracting rows between two index labels

In this example, two index label of rows are passed and all the rows that fall between those two index label have been returned (Both index labels Inclusive).




# importing pandas package
import pandas as pd
  
# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")
  
# retrieving rows by loc method
rows = data.loc["Avery Bradley":"Isaiah Thomas"]
  
# checking data type of rows
print(type(rows))
  
# display
rows


Output:
As shown in the output image, all the rows that fall between passed two index labels are returned in the form of a data frame.



Previous Article
Next Article

Similar Reads

Select Rows & Columns by Name or Index in Pandas DataFrame using [ ], loc & iloc
Indexing in Pandas means selecting rows and columns of data from a Dataframe. It can be selecting all the rows and the particular number of columns, a particular number of rows, and all the columns or a particular number of rows and columns each. Indexing is also known as Subset selection. Creating a Dataframe to Select Rows & Columns in Pandas
10 min read
Extracting rows using Pandas .iloc[] in Python
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. here we are learning how to Extract rows using Pandas .iloc[] in Python. Pandas .iloc[] Syntax Syntax: pandas.DataFrame.iloc[] Paramete
7 min read
Python | Pandas Series.loc
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object suppo
2 min read
Pandas DataFrame.loc[] Method
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame loc[] SyntaxPandas
6 min read
Difference between loc() and iloc() in Pandas DataFrame
Pandas library of Python is very useful for the manipulation of mathematical data and is widely used in the field of machine learning. It comprises many methods for its proper functioning. loc() and iloc() are one of those methods. These are used in slicing data from the Pandas DataFrame. They help in the convenient selection of data from the DataF
5 min read
Extracting MAC address using Python
MAC address also known as physical address is the unique identifier that is assigned to the NIC (Network Interface Card) of the computer. NIC helps in connection of a computer with other computers in the network. MAC address is unique for all the NIC's. Uses of MAC address : Useful in places where IP address change frequently. Helps network admin.
3 min read
Extracting email addresses using regular expressions in Python
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression. Let take an example in which we have to find out only email from the given input by Regular Expression. Examples: In
3 min read
Extracting Tweets containing a particular Hashtag using Python
Twitter is one of the most popular social media platforms. The Twitter API provides the tools you need to contribute to, engage with, and analyze the conversation happening on Twitter, which finds a lot of application in fields like Data Analytics and Artificial Intelligence. This article focuses on how to extract tweets having a particular Hashtag
4 min read
Extracting locations from text using Python
In this article, we are going to see how to extract location from text using Python. While working with texts, the requirement can be the detection of cities, regions, states, and countries and relationships between them in the received text. This can be very useful for geographical studies. In this article, we will use the locationtagger library.
3 min read
Extracting patches from large images using Python
In this article, we are going to look at how we can extract patches from large images in Python. We will be using the patchify library to extract patches from images. Patchy is a Python library that can split images into small overlap able patches by given patch cell size, and merge patches into the original images. We prefer to utilize small photo
2 min read
Extracting text from HTML file using Python
Extracting text from an HTML file is a common task in web scraping and data extraction. Python provides powerful libraries such as BeautifulSoup that make this task straightforward. In this article we will explore the process of extracting text from an HTML file using Python. Use the below command to install the BeautifulSoup library: pip install b
3 min read
Extracting an attribute value with beautifulsoup in Python
Prerequisite: Beautifulsoup Installation Attributes are provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. A tag may have any number of attributes. For example, the tag <b class="active"> has an attribute “cl
2 min read
NLP | Extracting Named Entities
Recognizing named entity is a specific kind of chunk extraction that uses entity tags along with chunk tags. Common entity tags include PERSON, LOCATION and ORGANIZATION. POS tagged sentences are parsed into chunk trees with normal chunking but the trees labels can be entity tags in place of chunk phrase tags. NLTK has already a pre-trained named e
2 min read
Extracting the real and imaginary parts of an NumPy array of complex numbers
Numpy library gives us functions such as real() and imag() to find real and imaginary parts of a complex number. real() : To find real part of the complex number imag() : To find imaginary part of the complex number Example 1 : # importing the module import numpy as np # creating a NumPy array complex_num = np.array([-1 + 9j, 2 - 77j, 31 - 25j, 40
2 min read
Extracting Code From GeeksForGeeks Article
Prerequisite: bs4requestsModules Neededrequests- Requests allows you to send HTTP/1.1 requests extremely easily. This module also doesn't come built-in with Python. To install simply type the given command in the terminal.pip install requestsbs4 :- Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does
2 min read
PySpark - Extracting single value from DataFrame
In this article, we are going to extract a single value from the pyspark dataframe columns. To do this we will use the first() and head() functions. Single value means only one value, we can extract this value based on the column name Syntax: dataframe.first()['column name']Dataframe.head()['Index'] Where, dataframe is the input dataframe and colum
2 min read
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas
Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods. 1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame : Pandas head() method is used to return top n (5 by default) rows of a data frame or series Syntax: Dataframe.head(n). Parameters: (optional) n is integer value,
2 min read
Python | Delete rows/columns from DataFrame using Pandas.drop()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages which makes importing and analyzing data much easier. In this article, we will how to delete a row in Excel using Pandas as well as delete a column from DataFrame using Pandas. Pandas Data
4 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
How to Filter rows using Pandas Chaining?
In this article, we will learn how to filter rows using Pandas chaining. For this first we have to look into some previous terms which are given below : Pandas DataFrame: It is a two-dimensional data structure, i.e. the data is tabularly aligned in rows and columns. The Pandas DataFrame has three main components i.e. data, rows, and columns.Pandas
4 min read
Select rows that contain specific text using Pandas
While preprocessing data using pandas dataframe there may be a need to find the rows that contain specific text. In this article we will discuss methods to find the rows that contain specific text in the columns or rows of a dataframe in pandas. Dataset in use: jobAge_RangeSalaryCredit-RatingSavingsBuys_HoneOwnMiddle-agedHighFair10000YesGovtYoungLo
3 min read
Concatenate strings from several rows using Pandas groupby
Pandas Dataframe.groupby() method is used to split the data into groups based on some criteria. The abstract definition of grouping is to provide a mapping of labels to the group name. To concatenate string from several rows using Dataframe.groupby(), perform the following steps: Group the data using Dataframe.groupby() method whose attributes you
1 min read
How to display all rows from dataframe using Pandas
In this article, we will discuss how to display all rows from dataframe using Pandas in Python. We will discuss different methods by which we can display all rows from dataframe using Pandas. Create a Diabetes Dataframe and Display all Rows from DataframeWhen we try to print a large data frame that exceeds the predefined number of rows and columns
6 min read
Limited rows selection with given column in Pandas | Python
Methods in Pandas like iloc[], iat[] are generally used to select the data from a given dataframe. In this article, we will learn how to select the limited rows with given columns with the help of these methods. Example 1: Select two columns # Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['
2 min read
Get all rows in a Pandas DataFrame containing given substring
Let's see how to get all rows in a Pandas DataFrame containing given substring with the help of different examples. Code #1: Check the values PG in column Position # importing pandas import pandas as pd # Creating the dataframe with dict of lists df = pd.DataFrame({'Name': ['Geeks', 'Peter', 'James', 'Jack', 'Lisa'], 'Team': ['Boston', 'Boston', 'B
3 min read
How to iterate over rows in Pandas Dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Let’s see the how to iterate over rows in Pandas Dataframe using iterrows() and itertuples() :Method #1: Using the DataFrame.iterrows() m
2 min read
Sorting rows in pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). We often need to do certain operations on both rows and column while handling the data. Let’s see how to sort rows in pandas DataFrame. Code #1: Sorting rows by Science # import modules import pandas as pd # creat
2 min read
Grouping Rows in pandas
Pandas is the most popular Python library that is used for data analysis. It provides highly optimized performance with back-end source code is purely written in C or Python. Let's see how to group rows in Pandas Dataframe with help of multiple examples. Example 1: For grouping rows in Pandas, we will start with creating a pandas dataframe first. #
2 min read
Ranking Rows of Pandas DataFrame
To rank the rows of Pandas DataFrame we can use the DataFrame.rank() method which returns a rank of every respective index of a series passed. The rank is returned on the basis of position after sorting. Example #1 : Here we will create a DataFrame of movies and rank them based on their ratings. # import the required packages import pandas as pd #
2 min read
Create a list from rows in Pandas DataFrame | Set 2
In an earlier post, we had discussed some approaches to extract the rows of the dataframe as a Python's list. In this post, we will see some more methods to achieve that goal. Note : For link to the CSV file used in the code, click here. Solution #1: In order to access the data of each row of the Pandas dataframe, we can use DataFrame.iloc attribut
2 min read