Home >Backend Development >Python Tutorial >How to Efficiently Set Values in Pandas DataFrame Cells by Index?
Setting Values in Pandas DataFrame Cells by Index
To set a specific cell value in a Pandas DataFrame based on its index, consider the following:
Using df.set_value(index, column, value)
df.set_value() allows you to directly assign a value to a cell using its index. However, note that this method is slated for deprecation.
# Correct way: df.set_value('C', 'x', 10)
Using df.at[index, column] = value
The preferred alternative is to use df.at[] to update cell values directly. This method is more efficient and provides a more concise syntax.
df.at['C', 'x'] = 10
Using Chained Indexing
Caution: While it might seem intuitive to use chained indexing to set cell values (e.g., df.xs('C')['x'] = 10), this method only modifies a copy of the row or column. To modify the original DataFrame directly, use either df.set_value() or df.at[].
Why Chained Indexing Fails
Chained indexing (e.g., df.xs('C')['x'] = 10) creates a new DataFrame object with a reference to the original data. Assignments made to this new object are not propagated to the original DataFrame.
Performance
Benchmarks show that df.set_value() is the fastest option, followed by df'x' = 10 and df.at['C', 'x'] = 10. However, performance differences can vary depending on DataFrame size and complexity.
The above is the detailed content of How to Efficiently Set Values in Pandas DataFrame Cells by Index?. For more information, please follow other related articles on the PHP Chinese website!