Python 更改 pandas DataFrame 中的特定列名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20868394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing a specific column name in pandas DataFrame
提问by Mark Graph
I was looking for an elegant way to change a specified column name in a DataFrame.
我正在寻找一种优雅的方式来更改DataFrame.
play data ...
播放数据...
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)
The most elegant solution I have found so far ...
迄今为止我发现的最优雅的解决方案......
names = df.columns.tolist()
names[names.index('two')] = 'new_name'
df.columns = names
I was hoping for a simple one-liner ... this attempt failed ...
我希望有一个简单的单线……这次尝试失败了……
df.columns[df.columns.tolist().index('one')] = 'another_name'
Any hints gratefully received.
感谢您收到任何提示。
采纳答案by Nipun Batra
A one liner does exist:
确实存在单班轮:
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
Following is the docstring for the renamemethod.
以下是该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)
回答by Jeong-Yoon Lee
Since inplaceargument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:
由于inplace参数可用,您不需要复制原始数据帧并将其分配回自身,而是执行以下操作:
df.rename(columns={'two':'new_name'}, inplace=True)
回答by Jacob H
What about?
关于什么?
df.columns.values[2] = "new_name"
回答by Ted Petrou
Pandas 0.21 now has an axis parameter
Pandas 0.21 现在有一个轴参数
The rename method has gained an axis parameter to match most of the rest of the pandas API.
重命名方法获得了一个轴参数以匹配大部分其余的 Pandas API。
So, in addition to this:
所以,除此之外:
df.rename(columns = {'two':'new_name'})
You can do:
你可以做:
df.rename({'two':'new_name'}, axis=1)
or
或者
df.rename({'two':'new_name'}, axis='columns')
回答by Naveen Reddy
For renaming the columns here is the simple one which will work for both Default(0,1,2,etc;)and existing columns but not much useful for a larger data sets(having many columns).
这里重命名列是一个简单的方法,它适用于Default(0,1,2,etc;)现有的列,但对较大的数据集(有很多列)没有多大用处。
For a larger data set we can slice the columns that we need and apply the below code:
对于更大的数据集,我们可以切片我们需要的列并应用以下代码:
df.columns = ['new_name','new_name1','old_name']
回答by Emmanuel Masabo
Following short code can help:
以下短代码可以提供帮助:
df3 = df3.rename(columns={c: c.replace(' ', '') for c in df3.columns})
Remove spaces from columns.
从列中删除空格。
回答by Nikhil VJ
If you know which column # it is (first / second / nth) then this solution posted on a similar question works regardless of whether it is named or unnamed, and in one line: https://stackoverflow.com/a/26336314/4355695
如果你知道它是哪一列(第一/第二/第 n)那么这个发布在类似问题上的解决方案不管它是命名还是未命名都有效,并且在一行中:https: //stackoverflow.com/a/26336314/ 4355695
df.rename(columns = {list(df)[1]:'new_name'}, inplace=True)
# 1 is for second column (0,1,2..)
回答by anka
Another option would be to simply copy & dropthe column:
另一种选择是简单地复制和删除列:
df = pd.DataFrame(d)
df['new_name'] = df['two']
df = df.drop('two', axis=1)
df.head()
After that you get the result:
之后你会得到结果:
one three new_name
0 1 a 9
1 2 b 8
2 3 c 7
3 4 d 6
4 5 e 5
回答by Kallol Medhi
pandas version 0.23.4
大熊猫版本 0.23.4
df.rename(index=str,columns={'old_name':'new_name'},inplace=True)
For the record:
作为记录:
omitting index=str will give error replace has an unexpected argument 'columns'
省略 index=str 将给出错误替换具有意外参数“列”

