<p>在pandas中,不能有两个名称完全相同的列,如果尝试创建另一个名为<code>Industrial production</code>的列,它将覆盖现有列:</p>
<pre><code>In [2]: df
Out[2]:
Region Industrial production
0 Italia 5669
1 Nord-ovest 1046
2 Piemonte 447
In [3]: second = df.columns[1]
In [4]: second
Out[4]: 'Industrial production'
In [5]: df[second] = second
In [6]: df
Out[6]:
Region Industrial production
0 Italia Industrial production
1 Nord-ovest Industrial production
2 Piemonte Industrial production
</code></pre>
<p>您需要为这个新列指定一个不同的名称,例如<code>Industrial production2</code>。然后,您可以按如下方式创建它:</p>
<pre><code>In [2]: df
Out[2]:
Region Industrial production
0 Italia 5669
1 Nord-ovest 1046
2 Piemonte 447
In [3]: second = df.columns[1]
In [3]: df[second + "2" ] = second
In [4]: df
Out[4]:
Region Industrial production Industrial production2
0 Italia 5669 Industrial production
1 Nord-ovest 1046 Industrial production
2 Piemonte 447 Industrial production
</code></pre>
<hr/>
<p>或者,您可以使用<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow noreferrer">df.assign</a>,如下所示:</p>
<pre><code>In [3]: df
Out[3]:
Region Industrial production
0 Italia 5669
1 Nord-ovest 1046
2 Piemonte 447
In [4]: df = df.assign(**{df.columns[1] + "2": df.columns[1]})
In [5]: df
Out[5]:
Region Industrial production Industrial production2
0 Italia 5669 Industrial production
1 Nord-ovest 1046 Industrial production
2 Piemonte 447 Industrial production
</code></pre>