Home > Backend Development > Python Tutorial > How to Efficiently Set Values in Pandas DataFrame Cells by Index?

How to Efficiently Set Values in Pandas DataFrame Cells by Index?

Linda Hamilton
Release: 2024-11-30 18:02:12
Original
645 people have browsed it

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)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template