更改pandas DataFram中的特定列名

2024-04-19 05:43:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在寻找一种优雅的方法来更改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'

感激地收到任何暗示。


Tags: columns数据方法nameimportdataframepandasdf
3条回答

由于inplace参数可用,您不需要复制原始数据帧并将其分配回自身,但请执行以下操作:

df.rename(columns={'two':'new_name'}, inplace=True)

存在一行:

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方法的docstring。

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)

怎么办?

df.columns.values[2] = "new_name"

相关问题 更多 >