The Wayback Machine - https://web.archive.org/web/20241007080745/https://www.geeksforgeeks.org/get-specific-row-from-pyspark-dataframe/
Open In App

Get specific row from PySpark dataframe

Last Updated : 18 Jul, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss how to get the specific row from the PySpark dataframe.

Creating Dataframe for demonstration:

Python3




# importing module
import pyspark
  
# importing sparksession
# from pyspark.sql module
from pyspark.sql import SparkSession
  
# creating sparksession
# and giving an app name
spark = SparkSession.builder.appName('sparkdf').getOrCreate()
  
# list  of employee data with 5 row values
data = [["1", "sravan", "company 1"],
        ["2", "ojaswi", "company 2"],
        ["3", "bobby", "company 3"],
        ["4", "rohith", "company 2"],
        ["5", "gnanesh", "company 1"]]
  
# specify column names
columns = ['Employee ID', 'Employee NAME',
           'Company Name']
  
# creating a dataframe from the lists of data
dataframe = spark.createDataFrame(data, columns)
  
# display dataframe
dataframe.show()


Output:

Method 1: Using collect()

This is used to get the all row’s data from the dataframe in list format.

Syntax: dataframe.collect()[index_position]

Where,

  • dataframe is the pyspark dataframe
  • index_position is the index row in dataframe

Example: Python code to access rows

Python3




# get first row
print(dataframe.collect()[0])
  
# get second row
print(dataframe.collect()[1])
  
# get last row
print(dataframe.collect()[-1])
  
# get third row
print(dataframe.collect()[2])


Output:

Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)

Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)

Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)

Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)

Method 2: Using show()

This function is used to get the top n rows from the pyspark dataframe.

Syntax: dataframe.show(no_of_rows)

where, no_of_rows is the row number to get the data

Example: Python code to get the data using show() function

Python3




# display dataframe only top 2 rows
print(dataframe.show(2))
  
# display dataframe only top 1 row
print(dataframe.show(1))
  
# display dataframe 
print(dataframe.show())


Output:

Method 3: Using first()

This function is used to return only the first row in the dataframe.

Syntax: dataframe.first()

Example: Python code to select the first row in the dataframe.

Python3




# display first row of the dataframe
print(dataframe.first())


Output:

Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)

Method 4: Using head()

This method is used to display top n rows in the dataframe.

Syntax: dataframe.head(n)

where, n is the number of rows to be displayed

Example: Python code to display the number of rows to be displayed.

Python3




# display only 1 row
print(dataframe.head(1))
  
# display only top 3  rows
print(dataframe.head(3))
  
# display only top 2 rows
print(dataframe.head(2))


Output:

[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)]

[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), 

Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′), 

Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)]

[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), 

Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)]

Method 5: Using tail()

Used to return last n rows in the dataframe

Syntax: dataframe.tail(n)

where n is the no of rows to be returned from last in the dataframe.

Example: Python code to get last n rows

Python3




# display only 1 row from last
print(dataframe.tail(1))
  
# display only top 3  rows from last
print(dataframe.tail(3))
  
# display only top 2 rows from last
print(dataframe.tail(2))


Output:

[Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]

[Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′),

 Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′),

  Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]

[Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′),

 Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]

Method 6: Using select() with collect() method

This method is used to select a particular row from the dataframe, It can be used with collect() function.

Syntax: dataframe.select([columns]).collect()[index]

where, 

  • dataframe is the pyspark dataframe
  • Columns is the list of columns to be displayed in each row
  • Index is the index number of row to be displayed.

Example: Python code to select the particular row.

Python3




# select first row
print(dataframe.select(['Employee ID',
                        'Employee NAME',
                        'Company Name']).collect()[0])
  
# select third row
print(dataframe.select(['Employee ID',
                        'Employee NAME',
                        'Company Name']).collect()[2])
  
# select forth row
print(dataframe.select(['Employee ID',
                        'Employee NAME',
                        'Company Name']).collect()[3])


Output:

Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)

Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)

Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′)

Method 7: Using take() method

This method is also used to select top n rows

Syntax: dataframe.take(n)

where n is the number of rows to be selected

Python3




# select top 2 rows
print(dataframe.take(2))
  
# select top 4 rows
print(dataframe.take(4))
  
# select top 1 row
print(dataframe.take(1))


Output:

[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), 

Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)]

[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′),

Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′),

 Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′),

  Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′)]

[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)]



Similar Reads

How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
How to get a value from the Row object in PySpark Dataframe?
In this article, we are going to learn how to get a value from the Row object in PySpark DataFrame. Method 1 : Using __getitem()__ magic method We will create a Spark DataFrame with at least one row using createDataFrame(). We then get a Row object from a list of row objects returned by DataFrame.collect(). We then use the __getitem()__ magic metho
5 min read
Get a specific row in a given Pandas DataFrame
In the Pandas DataFrame, we can find the specified row value with the function iloc(). In this function, we pass the row number as a parameter. In this article, we will see how we can get a specific row in a given Pandas Dataframe. pandas.DataFrame.iloc[] Function SyntaxSyntax : pandas.DataFrame.iloc[] Parameters : Index Position : Index position o
4 min read
Removing duplicate rows based on specific column in PySpark DataFrame
In this article, we are going to drop the duplicate rows based on a specific column from dataframe using pyspark in Python. Duplicate data means the same data based on some condition (column values). For this, we are using dropDuplicates() method: Syntax: dataframe.dropDuplicates(['column 1','column 2','column n']).show() where, dataframe is the in
1 min read
Select specific column of PySpark dataframe with its position
In this article, we will discuss how to select a specific column by using its position from a pyspark dataframe in Python. For this, we will use dataframe.columns() method inside dataframe.select() method. Syntax: dataframe.select(dataframe.columns[column_number]).show() where, dataframe is the dataframe namedataframe.columns[]: is the method which
2 min read
Drop rows containing specific value in PySpark dataframe
In this article, we are going to drop the rows with a specific value in pyspark dataframe. Creating dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('spark
2 min read
How to select last row and access PySpark dataframe by index ?
In this article, we will discuss how to select the last row and access pyspark dataframe by index. Creating dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appNam
2 min read
How to loop through each row of dataFrame in PySpark ?
In this article, we are going to see how to loop through each row of Dataframe in PySpark. Looping through each row helps us to perform complex operations on the RDD or Dataframe. Creating Dataframe for demonstration: C/C++ Code # importing necessary libraries import pyspark from pyspark.sql import SparkSession # function to create new SparkSession
5 min read
Filtering a row in PySpark DataFrame based on matching values from a list
In this article, we are going to filter the rows in the dataframe based on matching values in the list by using isin in Pyspark dataframe isin(): This is used to find the elements contains in a given dataframe, it will take the elements and get the elements to match to the data Syntax: isin([element1,element2,.,element n]) Create Dataframe for demo
2 min read
How to duplicate a row N time in Pyspark dataframe?
In this article, we are going to learn how to duplicate a row N times in a PySpark DataFrame. Method 1: Repeating rows based on column value In this method, we will first make a PySpark DataFrame using createDataFrame(). In our example, the column "Y" has a numerical value that can only be used here to repeat rows. We will use withColumn() function
4 min read
How take a random row from a PySpark DataFrame?
In this article, we are going to learn how to take a random row from a PySpark DataFrame in the Python programming language. Method 1 : PySpark sample() method PySpark provides various methods for Sampling which are used to return a sample from the given PySpark DataFrame. Here are the details of the sample() method : Syntax : DataFrame.sample(with
4 min read
Convert PySpark Row List to Pandas DataFrame
In this article, we will convert a PySpark Row List to Pandas Data Frame. A Row object is defined as a single Row in a PySpark DataFrame. Thus, a Data Frame can be easily represented as a Python List of Row objects. Method 1 : Use createDataFrame() method and use toPandas() method Here is the syntax of the createDataFrame() method : Syntax : curren
4 min read
Custom row (List of CustomTypes) to PySpark dataframe
In this article, we are going to learn about the custom row (List of Custom Types) to PySpark data frame in Python. We will explore how to create a PySpark data frame from a list of custom objects, where each object represents a row in the data frame. PySpark data frames are a powerful and efficient tool for working with large datasets in a distrib
6 min read
Apply same function to all fields of PySpark dataframe row
Are you a data scientist or data analyst who handles a lot of data? Have you ever felt the need to apply the same function whether it is uppercase, lowercase, subtract, add, etc. to apply to all the fields of data frame rows? This is possible in Pyspark in not only one way but numerous ways. In this article, we will discuss all the ways to apply th
6 min read
Split Dataframe in Row Index in Pyspark
In this article, we are going to learn about splitting Pyspark data frame by row index in Python. In data science. there is a bulk of data and their is need of data processing and lots of modules, functions and methods are available to process data. In this article we are going to process data by splitting dataframe by row indexing using Pyspark in
5 min read
PySpark Row using on DataFrame and RDD
You can access the rows in the data frame like this: Attribute, dictionary value. Row allows you to create row objects using named arguments. A named argument cannot be omitted to indicate that the value is "none" or does not exist. In this case, you should explicitly set this to None. Subsequent changes in version 3.0.0: Rows created from named ar
6 min read
How to get name of dataframe column in PySpark ?
In this article, we will discuss how to get the name of the Dataframe column in PySpark. To get the name of the columns present in the Dataframe we are using the columns function through this function we will get the list of all the column names present in the Dataframe. Syntax: df.columns We can also get the names of the columns from the list of S
3 min read
Get number of rows and columns of PySpark dataframe
In this article, we will discuss how to get the number of rows and the number of columns of a PySpark dataframe. For finding the number of rows and number of columns we will use count() and columns() with len() function respectively. df.count(): This function is used to extract number of rows from the Dataframe.df.distinct().count(): This functions
6 min read
How to get distinct rows in dataframe using PySpark?
In this article we are going to get the distinct data from pyspark dataframe in Python, So we are going to create the dataframe using a nested list and get the distinct data. We are going to create a dataframe from pyspark list bypassing the list to the createDataFrame() method from pyspark, then by using distinct() function we will get the distinc
2 min read
How to Get substring from a column in PySpark Dataframe ?
In this article, we are going to see how to get the substring from the PySpark Dataframe column and how to create the new column and put the substring in that newly created column. We can get the substring of the column using substring() and substr() function. Syntax: substring(str,pos,len) df.col_name.substr(start, length) Parameter: str - It can
3 min read
Get value of a particular cell in PySpark Dataframe
In this article, we are going to get the value of a particular cell in the pyspark dataframe. For this, we will use the collect() function to get the all rows in the dataframe. We can specify the index (cell positions) to the collect function Creating dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession
2 min read
Get current number of partitions of a DataFrame - Pyspark
In this article, we are going to learn how to get the current number of partitions of a data frame using Pyspark in Python. In many cases, we need to know the number of partitions in large data frames. Sometimes we have partitioned the data and we need to verify if it has been correctly partitioned or not. There are various methods to get the curre
6 min read
Converting Row into list RDD in PySpark
In this article, we are going to convert Row into a list RDD in Pyspark. Creating RDD from Row for demonstration: C/C++ Code # import Row and SparkSession from pyspark.sql import SparkSession, Row # create sparksession spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate() # create student data with Row function data = [Row(name=
1 min read
Building a row from a dictionary in PySpark
In this article, we will discuss how to build a row from the dictionary in PySpark For doing this, we will pass the dictionary to the Row() method. Syntax: Syntax: Row(dict) Example 1: Build a row with key-value pair (Dictionary) as arguments. Here, we are going to pass the Row with Dictionary Syntax: Row({'Key':"value", 'Key':"value",'Key':"value"
1 min read
PySpark Row-Wise Function Composition
An interface for Apache Spark in Python is known as Pyspark. While coding in Pyspark, have you ever felt the need to apply the function row-wise and produce the result? Don't know how to achieve this? Continue reading this article further. In this article, we will discuss how to apply row-wise function composition on Pyspark data frame in Python. P
3 min read
How to get column and row names in DataFrame?
While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names and columns names in order to perform certain operations. Note: For downloading the nba dataset used in the below examples Click Here Getting row names in Pandas dataframe First, let's create a simple dataframe with nba.csv C/C++ Code #
3 min read
Get the specified row value of a given Pandas DataFrame
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Now let's see how to get the specified row value of a given DataFrame. We shall be using loc[ ], iloc[ ], and [ ] for a data frame object to select rows and columns from our data frame. iloc[ ] is used to select
2 min read
How to Get First Row of Pandas DataFrame?
In this article, we will discuss how to get the first row of the Pandas Dataframe Get the First Row of Pandas using iloc[] This method is used to access the row by using row numbers. We can get the first row by using 0 indexes. Example 1: Python code to get the first row of the Dataframe by using the iloc[] function C/C++ Code # import pandas modul
4 min read
Select columns in PySpark dataframe
In this article, we will learn how to select columns in PySpark dataframe. Function used: In PySpark we can select columns using the select() function. The select() function allows us to select single or multiple columns in different formats. Syntax: dataframe_name.select( columns_names ) Note: We are specifying our path to spark directory using th
4 min read
How to create a PySpark dataframe from multiple lists ?
In this article, we will discuss how to create Pyspark dataframe from multiple lists. ApproachCreate data from multiple lists and give column names in another list. So, to do our task we will use the zip method. zip(list1,list2,., list n) Pass this zipped data to spark.createDataFrame() method dataframe = spark.createDataFrame(data, columns) Exampl
2 min read
Article Tags :
Practice Tags :