我有以下带有两个头的数据文件。我需要创建一个具有第二个标题(工业数据集)字符串值的新列。
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发布于 2018-12-07 16:45:39
在熊猫中,不能有两个名称完全相同的列,如果您尝试创建另一个名为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发布于 2018-12-07 16:38:12
如果要将其作为索引,则可以使用:
df.set_index([list(df.columns.values)1],inplace=True)。
这将采用第二列,或者您可以直接写入第二列标题的名称。代码将是一些什么接近这一点。希望这能帮上忙
https://stackoverflow.com/questions/53673485
复制相似问题