Set value for particular cell in pandas DataFrame using index
In pandas, you can set the value of a specific cell in a DataFrame using the at
method. The at
method allows you to set the value of a cell by specifying the index of the row and column.
For example, suppose you have a DataFrame called df
and you want to set the value of the cell at row index 2 and column 'B' to 5:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.at[2, 'B'] = 5
print(df)
Alternatively, you can use the iat
method which allows you to set the value of a cell by specifying the index of the row and column using integer based location.
df.iat[2, 1] = 5
You can also use the loc
method which allows you to set the value of a cell by specifying the label of the row and column.
df.loc[2, 'B'] = 5
It's worth noting that, these methods are efficient and faster than other common methods like df.ix[]
, df.iloc[]
, and df[]
when it comes to setting the value of a single cell.
Please keep in mind that, these methods will raise a `KeyError `trigger if the index or column label does not exist.