<p>问题在于<a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy">chained indexing</a>,实际上您要做的是将值设置为-<code>pop[pop['Year'] == 2014]['Country Name']</code>-这在大多数情况下都不起作用(在链接的文档中解释得很好),因为这是两个不同的调用,其中一个调用可能返回数据帧的副本(我相信布尔索引)返回数据帧的副本。</p>
<p>因此,当您尝试设置该副本的值时,它不会反映在原始数据帧中。示例-</p>
<pre><code>In [6]: df
Out[6]:
A B
0 1 2
1 3 4
2 4 5
3 6 7
4 8 9
In [7]: df[df['A']==1]['B'] = 10
/path/to/ipython-script.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
if __name__ == '__main__':
In [8]: df
Out[8]:
A B
0 1 2
1 3 4
2 4 5
3 6 7
4 8 9
</code></pre>
<hr/>
<p>如前所述,您应该使用<code>DataFrame.loc</code>来索引要在单个调用中更新的行和列,而不是链式索引,从而避免此错误。示例-</p>
<pre><code>pop.loc[(pop['year'] == 2014), 'Country Name'] = pop.loc[(pop['year'] == 2014), 'Country Name'].map(f)
</code></pre>
<p>或者,如果这对您来说太长,您可以预先创建一个掩码(boolean dataframe)并分配给一个变量,并在上面的语句中使用它。示例-</p>
<pre><code>mask = pop['year'] == 2014
pop.loc[mask,'Country Name'] = pop.loc[mask,'Country Name'].map(f)
</code></pre>
<p>演示-</p>
<pre><code>In [9]: df
Out[9]:
A B
0 1 2
1 3 4
2 4 5
3 6 7
4 8 9
In [10]: mapping = { 1:2 , 3:4}
In [11]: f= lambda x: mapping.get(x, x)
In [12]: df.loc[(df['B']==2),'A'] = df.loc[(df['B']==2),'A'].map(f)
In [13]: df
Out[13]:
A B
0 2 2
1 3 4
2 4 5
3 6 7
4 8 9
</code></pre>
<p>使用<em>掩码</em>方法演示-</p>
<pre><code>In [18]: df
Out[18]:
A B
0 1 2
1 3 4
2 4 5
3 6 7
4 8 9
In [19]: mask = df['B']==2
In [20]: df.loc[mask,'A'] = df.loc[mask,'A'].map(f)
In [21]: df
Out[21]:
A B
0 2 2
1 3 4
2 4 5
3 6 7
4 8 9
</code></pre>