使用第二个标题的字符串值创建新列

2024-05-23 19:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两个标题的数据帧。我需要使用第二个标题(Industrial dataset)的字符串值创建一个新列

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

Tags: 数据字符串标题datasetregionproductionindustrialnord
2条回答

在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

如果要将其作为索引,则可以使用:

set_索引([list(df.columns.values)[1]],inplace=True)

这将占用第二列,或者您可以直接写入第二列标题的名称。代码将与此接近。 希望这有帮助

相关问题 更多 >