Set value for particular cell in pandas DataFrame using index
Going forward, the recommended method is
df.xs('C')['x']=10 does not work:
df.xs('C') by default, returns a new dataframe with a copy of the data, so
modifies this new dataframe only.
df['x'] returns a view of the
df dataframe, so
df['x']['C'] = 10
Warning: It is sometimes difficult to predict if an operation returns a copy or a view. For this reason the docs recommend avoiding assignments with "chained indexing".
So the recommended alternative is
df.at['C', 'x'] = 10
which does modify
In : %timeit df.set_value('C', 'x', 10)100000 loops, best of 3: 2.9 µs per loopIn : %timeit df['x']['C'] = 10100000 loops, best of 3: 6.31 µs per loopIn : %timeit df.at['C', 'x'] = 10100000 loops, best of 3: 9.2 µs per loop
.set_value method is going to be deprecated.
.iat/.at are good replacements, unfortunately pandas provides little documentation
The fastest way to do this is using set_value. This method is ~100 times faster than
.ix method. For example:
df.set_value('C', 'x', 10)
You can also use a conditional lookup using
.loc as seen here:
df.loc[df[<some_column_name>] == <condition>, [<another_column_name>]] = <value_to_add>
<some_column_name is the column you want to check the
<condition> variable against and
<another_column_name> is the column you want to add to (can be a new column or one that already exists).
<value_to_add> is the value you want to add to that column/row.
This example doesn't work precisely with the question at hand, but it might be useful for someone wants to add a specific value based on a condition.