首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建具有第二个标头字符串值的新列

创建具有第二个标头字符串值的新列
EN

Stack Overflow用户
提问于 2018-12-07 16:32:23
回答 2查看 30关注 0票数 0

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

代码语言:javascript
复制
Region           Industrial production                                                          
Italia           5669   
Nord-ovest       1046   
Piemonte         447 

我的最后输出需要:

代码语言:javascript
复制
Industrial production   Region  Industrial production
Industrial production   Italia                   5669
Industrial production   Nord-ovest               1046
Industrial production   Piemonte                  447
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-07 16:45:39

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

代码语言:javascript
复制
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。然后,您可以如下所示创建它:

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2018-12-07 16:38:12

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

df.set_index([list(df.columns.values)1],inplace=True)。

这将采用第二列,或者您可以直接写入第二列标题的名称。代码将是一些什么接近这一点。希望这能帮上忙

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53673485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档