python - 使用第二个标题的字符串值创建新列
问题描述
我有以下带有两个标头的数据框。我需要使用第二个标题的字符串值创建一个新列(工业数据集)
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
解决方案
在 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
推荐阅读
- apache-kafka - Debezium - MySQL 连接器 - Kinesis - 服务未启动
- r - 不能通过在 R 中使用带有选择器的 cbind() 来对数据帧进行子集化
- python - django.db.utils.OperationalError:1170
- sql - 如何在 SQL 中使用 Distinct inside join
- css - 当默认为 row 时,div 容器在不同的行上
- r - 用 as.POSIXct() 转换 R 中的日期返回 NA
- javascript - 我有一段代码我无法理解
- ios - 如果一个部分被展开,那么所有其他部分都应该在 Swift 5 的表格视图中折叠。我应该如何实现这个
- mysql - 客户在一个月内的交易计数
- spring - aspectj 注释不适用于 flink