How to Set the Value of a Particular Cell in a DataFrame Using the Index?

Set Value Particular Cell DataFrame Using Index Pandas Pyspark

DataFrame is a two-dimensional data structure with labeled rows and columns. We can use the labels (i.e. index) to access a particular cell. Row and column indices can be considered as the address of a cell.

In this short how-to article, we will learn how to set the value of a cell in Pandas and PySpark DataFrames using the cell index.

How to Set the Value of a Particular Cell in a DataFrame Using the Index?

Pandas

We can use both the loc and iloc methods for this task. Loc uses labels whereas iloc works with index values.

Consider the DataFrame shown in the above drawing. We want to change the value of the cell in green. Its address in terms of labels is ā€œ1-Cā€. In the case of using indices, the address is ā€œ1-2ā€

				
					# with loc
df.loc[1, "C"] = 20

# with iloc
df.iloc[1, 2] = 20
				
			

The row labels are the same as row indices unless we assign a customized index to the DataFrame.

PySpark

We can use the collect method to get the value in a particular cell.

				
					# with index
df.collect()[1][2]
15

# with labels
df.collect()[1]["C"]
15
				
			

However, PySpark does not allow assigning a new value to a particular cell.

This question is also being asked as:

  • How to set values in a DataFrame based on index?

People have also asked for:

You may also like

Start Monitoring Your Models in Minutes