Home >Backend Development >Python Tutorial >How to Efficiently Set a Specific Cell Value in a Pandas DataFrame?

How to Efficiently Set a Specific Cell Value in a Pandas DataFrame?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 17:28:11382browse

How to Efficiently Set a Specific Cell Value in a Pandas DataFrame?

Set Value for a Specific Cell in a Pandas DataFrame

You've created a DataFrame and want to change the value of a particular cell. However, using df.xs('C')['x'] = 10 doesn't update the DataFrame as expected. Why?

The problem stems from how df.xs() operates. By default, it returns a new DataFrame with a copy of the data. So, df.xs('C')['x'] = 10 modifies only the new DataFrame, not the original.

Instead, you can use df['x']['C'] = 10. This method returns a view of the original DataFrame, and any modifications will be applied to df.

However, the recommended approach is using .at or .iat:

  • df.at['C', 'x'] = 10: Sets the value at row 'C' and column 'x' directly.
  • df.iat[2, 0] = 10: Accesses the cell using its index position (2 for row, 0 for column).

Why is df.xs('C')['x'] = 10 deprecated?

df.set_value('C', 'x', 10) is the preferred method because it's significantly faster. However, df.set_value() is slated for deprecation.

Performance Comparison

Benchmarks show that df.set_value() outperforms other options in terms of speed:

In [18]: %timeit df.set_value('C', 'x', 10)
100000 loops, best of 3: 2.9 µs per loop

In [20]: %timeit df['x']['C'] = 10
100000 loops, best of 3: 6.31 µs per loop

In [81]: %timeit df.at['C', 'x'] = 10
100000 loops, best of 3: 9.2 µs per loop

The above is the detailed content of How to Efficiently Set a Specific Cell Value in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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