How to set value for particular cell in pandas DataFrame using index?
When you have a specific row index (label) and column name (label) and want to assign a new value to exactly one cell, you can use any of the following approaches:
1. Using loc
(label-based)
import pandas as pd df = pd.DataFrame({ "A": [10, 20, 30], "B": [40, 50, 60] }, index=["row1", "row2", "row3"]) # Set value for row with label 'row2' and column 'B' df.loc["row2", "B"] = 999 print(df)
df.loc[row_label, column_label] = new_value
uses the label of the row (and column) rather than position.- This is the most common approach when your DataFrame has meaningful row labels (like 'row2') and named columns.
2. Using at
(faster access for a single cell)
If you’re only updating one cell, df.at
is optimized for speed:
# Equivalent to using loc but typically faster for a single cell df.at["row2", "B"] = 999
at
andloc
both rely on labels (not integer positions).df.at[row_label, col_label]
is a direct scalar setter/getter and is preferable for single-element access when performance matters.
3. Using iat
(integer-based access)
If your DataFrame index is integer-based or if you just prefer using integer row and column positions:
df2 = pd.DataFrame({ "A": [10, 20, 30], "B": [40, 50, 60] }) # Set value in row 1 (second row), column 1 (second column) df2.iat[1, 1] = 999 print(df2)
df.iat[row_position, col_position] = value
uses integer positions for rows and columns (0-based).- This is similar to NumPy’s indexing logic (e.g.,
[row, column]
).
4. Considerations
-
Row Labels vs. Positions
- Use
.loc
/.at
if your DataFrame has custom string labels or if you explicitly want to reference row/column names. - Use
.iat
if you prefer integer positions and your DataFrame is aligned that way.
- Use
-
Performance
at
andiat
are slightly more performant for single-element access, whileloc
andiloc
can handle more complex indexing tasks (e.g., slicing multiple rows/columns).
-
In-Place Modification
- All these approaches modify the DataFrame in place. Ensure you keep a copy if you don’t want to change the original.
Boost Your Python Skills
To tackle more advanced data manipulation challenges or simply write more efficient code, a solid foundation in Python is essential. Grokking Python Fundamentals by DesignGurus.io helps you build that foundation—from core Python syntax and data structures to best practices—so you can handle everything from basic DataFrame edits to more complex transformations with confidence.
By choosing the right approach (loc
, at
, iat
), you’ll be able to set values for individual cells accurately and efficiently in your Pandas workflows. Happy coding!