我一直在寻找一种优雅的方法来更改中的指定列名称DataFrame
。
播放数据...
import pandas as pd
d = {
'one': [1, 2, 3, 4, 5],
'two': [9, 8, 7, 6, 5],
'three': ['a', 'b', 'c', 'd', 'e']
}
df = pd.DataFrame(d)
到目前为止,我发现的最优雅的解决方案...
names = df.columns.tolist()
names[names.index('two')] = 'new_name'
df.columns = names
我希望有一个简单的单线...此尝试失败了...
df.columns[df.columns.tolist().index('one')] = 'another_name'
任何提示均感激不尽。
确实存在一个班轮:
In [27]: df=df.rename(columns = {'two':'new_name'})
In [28]: df
Out[28]:
one three new_name
0 1 a 9
1 2 b 8
2 3 c 7
3 4 d 6
4 5 e 5
以下是该rename
方法的文档字符串。
定义:df.rename(自身,索引=无,列=无,复制= True, 原地= False)文档字符串: 使用一个或多个输入函数更改索引和/或列 。函数/字典值必须唯一(1对1)。 字典/系列中未包含的标签将保持原样。 参数 ---------- index:类似于dict或函数,可选 转换以应用于索引值 列:dict-类似于或函数,可选 转换以应用于列值 复制:boolean,默认值True 也复制基础data inplace:布尔值,默认为False 是否返回新的DataFrame。如果为True,则将 忽略副本的值。 也可以看看 -------- Series.rename 返回 -------已 重命名:DataFrame(新对象)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句