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