How to Set Cell Value in Pandas DataFrame?

How to Set Cell Value in Pandas DataFrame?

To set a cell value in a pandas DataFrame, you can use either the .at[] method for fast access to a single cell by row/column labels, or the .loc[] method for label-based indexing. Let's look at both methods.

  1. Using .at[] method:

    This method is faster and is meant for accessing or setting a single cell by row/column labels.

    import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # Set value for the cell in the first row and first column to 100 df.at[0, 'A'] = 100 print(df) 
  2. Using .loc[] method:

    This method can be used for single cell access or slicing rows/columns based on labels.

    import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # Set value for the cell in the first row and first column to 100 df.loc[0, 'A'] = 100 print(df) 

Both methods will produce the following DataFrame:

 A B C 0 100 4 7 1 2 5 8 2 3 6 9 

Note: When setting a cell value, be cautious about chained indexing, like df[df['A'] > 2]['B'] = 50. It might not modify the original DataFrame due to the way the operations are chained together. Instead, you should use the .loc[] method for such conditional assignments.


More Tags

hal pty dismiss ssh-tunnel for-xml wsgi mplcursors jquery-ui django-class-based-views html-safe

More Programming Guides

Other Guides

More Programming Examples