<p><a href="https://stackoverflow.com/a/24517695/190597">RukTech's answer</a>,<code>df.set_value('C', 'x', 10)</code>比我下面建议的选项快得多。然而,它一直是<a href="https://github.com/pandas-dev/pandas/issues/15269" rel="noreferrer"><strong>slated for deprecation</strong></a>。</p>
<p>向前看,<a href="https://github.com/pandas-dev/pandas/issues/15269#issuecomment-276382712" rel="noreferrer">recommended method is ^{<cd2>}</a>。</p>
<hr/>
<p><strong>为什么<code>df.xs('C')['x']=10</code>不起作用:</strong></p>
<p><code>df.xs('C')</code>默认情况下,返回数据的新数据帧,因此</p>
<pre><code>df.xs('C')['x']=10
</code></pre>
<p>仅修改此新数据框。</p>
<p><code>df['x']</code>返回数据帧的视图,因此</p>
<pre><code>df['x']['C'] = 10
</code></pre>
<p>修改<code>df</code>本身。</p>
<p><strong>警告</strong>:有时很难预测操作是否返回副本或视图。因此<a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy" rel="noreferrer">docs recommend avoiding assignments with "chained indexing"</a>。</p>
<hr/>
<p>所以推荐的替代方案是</p>
<pre><code>df.at['C', 'x'] = 10
</code></pre>
<p>它可以修改<code>df</code>。</p>
<hr/>
<pre><code>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
</code></pre>