慕桂英4014372
重命名特定列使用df.rename()函数并引用要重命名的列。并不是所有的列都必须重命名:df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})# Or rename the existing DataFrame (rather than creating a copy)
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)最小代码示例df = pd.DataFrame('x', index=range(3), columns=list('abcde'))df
a b c d e0 x x x x x1 x x x x x2 x x x x x以下方法都工作并产生相同的输出:df2 = df.rename({'a': 'X', 'b': 'Y'}, axis=1) # new methoddf2 = df.rename({'a': 'X', 'b': 'Y'}, axis='columns')
df2 = df.rename(columns={'a': 'X', 'b': 'Y'}) # old method df2
X Y c d e0 x x x x x1 x x x x x2 x x x x x请记住将结果分配回原来的位置,因为修改是不到位的。或者,指定inplace=True:df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)df
X Y c d e0 x x x x x1 x x x x x2 x x x x x在v0.25中,还可以指定errors='raise'如果指定了无效的列到重命名,则引发错误。看见v0.25rename()博士.重新分配列标题使用df.set_axis()带着axis=1和inplace=False(交回副本)。df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1, inplace=False)df2
V W X Y Z0 x x x x x1 x x x x x2 x x x x x这将返回一个副本,但您可以通过设置inplace=True(这是版本<=0.24的默认行为,但将来可能会改变)。还可以直接分配标头:df.columns = ['V', 'W', 'X', 'Y', 'Z']df
V W X Y Z0 x x x x x1 x x x x x2 x x x x x
猛跑小猪
这个rename方法可以接受一个函数,例如:In [11]: df.columnsOut[11]: Index([u'$a', u'$b', u'$c', u'$d', u'$e'], dtype=object)In [12]: df.rename(columns=lambda x: x[1:],
inplace=True)In [13]: df.columnsOut[13]: Index([u'a', u'b', u'c', u'd', u'e'], dtype=object)