I have several columns in my dataframe that are unnamed except for a number. In this case, the columns are numbered 50 to 59. I want to rename the columns with year labels, i.e. column 50 would be renamed to '2006', column 51 renamed to '2007', and so forth.
我的数据框中有几列除了数字之外没有命名。在这种情况下,列编号为50到59.我想用年份标签重命名列,即列50将重命名为“2006”,第51列重命名为“2007”,依此类推。
I have the following code to rename the columns, which works, but it seems overly repetitive, in terms of how much typing I have to do:
我有以下代码重命名列,这是有效的,但它似乎过于重复,在我必须做多少输入:
GDP.rename(columns={50:'2006', 51:'2007', 52:'2008', 53:'2009',54:'2010', 55:'2011', 56:'2012', 57:'2013', 58:'2014', 59:'2015'}, inplace=True)
Is there a way to use the .rename()
method in a less verbose way
有没有办法以较简洁的方式使用.rename()方法
I feel I should be able to pass in a range of columns, such as [49:60] and a range of years [2006:2015] into the .rename()
method to achieve the same result.
我觉得我应该能够将一系列列,例如[49:60]和一系列年份[2006:2015]传递到.rename()方法中,以获得相同的结果。
1 个解决方案
#1
0
Yes, you have a couple of options.
是的,你有几个选择。
Option 1
Use a dictionary comprehension:
使用字典理解:
GDP.rename(columns={i: str(1956+i) for i in range(50, 60)}, inplace=True)
Option 2
Use a custom function. This can be an anonymous lambda
:
使用自定义功能。这可以是一个匿名的lambda:
GDP.rename(columns=lambda x: str(1956+x) if isinstance(x, int) else x, inplace=True)
#1
0
Yes, you have a couple of options.
是的,你有几个选择。
Option 1
Use a dictionary comprehension:
使用字典理解:
GDP.rename(columns={i: str(1956+i) for i in range(50, 60)}, inplace=True)
Option 2
Use a custom function. This can be an anonymous lambda
:
使用自定义功能。这可以是一个匿名的lambda:
GDP.rename(columns=lambda x: str(1956+x) if isinstance(x, int) else x, inplace=True)