首页 > 解决方案 > 使用第二个标题的字符串值创建新列

问题描述

我有以下带有两个标头的数据框。我需要使用第二个标题的字符串值创建一个新列(工业数据集)

Region           Industrial production                                                          
Italia           5669   
Nord-ovest       1046   
Piemonte         447 

我的最终输出需要是:

Industrial production   Region  Industrial production
Industrial production   Italia                   5669
Industrial production   Nord-ovest               1046
Industrial production   Piemonte                  447

标签: pythonstringpandasheaderrename

解决方案


在 pandas 中,您不能有两个名称完全相同的列,如果您尝试创建另一个名为Industrial production它的列,它将覆盖现有的列:

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

您需要给这个新列一个不同的名称,例如Industrial production2。然后您可以按如下方式创建它:

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

作为替代方案,您可以使用df.assign,如下所示:

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

推荐阅读