python - 更改 pandas DataFrame 中的特定列名

我正在寻找一种优雅的方式来更改 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 方法的文档字符串。

Definition: df.rename(self, index=None, columns=None, copy=True, inplace=False)
Docstring:
Alter index and / or columns using input function or
functions. Function / dict values must be unique (1-to-1). Labels not
contained in a dict / Series will be left as-is.

Parameters
----------
index : dict-like or function, optional
    Transformation to apply to index values
columns : dict-like or function, optional
    Transformation to apply to column values
copy : boolean, default True
    Also copy underlying data
inplace : boolean, default False
    Whether to return a new DataFrame. If True then value of copy is
    ignored.

See also
--------
Series.rename

Returns
-------
renamed : DataFrame (new object)

https://stackoverflow.com/questions/20868394/

相关文章:

regex - 如何使用 wget 下载整个目录和子目录?

python - Django CSRF 检查因 Ajax POST 请求而失败

python - 为什么元组可以包含可变项?

python - 迭代模板中的模型实例字段名称和值

linux - 我什么时候应该在 shell 变量周围加上引号?

linux - 当程序具有命令行参数时,如何使用 GDB 分析程序的核心转储文件?

linux - 您可以将 Amazon EBS 附加到多个实例吗?

python - Python 是否优化尾递归?

python - 如何检查有效的电子邮件地址?

linux - 移动除一个以外的所有文件