更改 pandas DataFrame 中的特定列名 [英] Changing a specific column name in pandas DataFrame

查看:96
本文介绍了更改 pandas DataFrame 中的特定列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种优雅的方式来更改 DataFrame 中的指定列名.

播放数据...

将pandas导入为pdd = {'一': [1, 2, 3, 4, 5],'二': [9, 8, 7, 6, 5],'三': ['a', 'b', 'c', 'd', 'e']}df = pd.DataFrame(d)

迄今为止我发现的最优雅的解决方案......

names = df.columns.tolist()名称[names.index('two')] = 'new_name'df.columns = 名称

我希望有一个简单的单线……这次尝试失败了……

df.columns[df.columns.tolist().index('one')] = 'another_name'

感谢收到任何提示.

解决方案

确实存在单行:

在[27]中:df=df.rename(columns = {'two':'new_name'})在 [28] 中:df出[28]:一三新名字0 1 一个 91 2 乙 82 3 73 4 d 64 5 5

以下是 rename 方法的文档字符串.

<前>定义:df.rename(self, index=None, columns=None, copy=True, inplace=False)文档字符串:使用输入函数更改索引和/或列或职能.函数/字典值必须是唯一的(1 对 1).标签不包含在 dict/Series 中的内容将保持原样.参数----------index : 类似字典或函数,可选应用于索引值的转换列:类似字典或函数,可选应用于列值的转换复制:布尔值,默认为真同时复制底层数据就地:布尔值,默认为 False是否返回一个新的 DataFrame.如果为 True,则副本的值为忽略.也可以看看--------系列.重命名退货-------重命名:DataFrame(新对象)

I was looking for an elegant way to change a specified column name in a 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.

解决方案

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 rename method.

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)

这篇关于更改 pandas DataFrame 中的特定列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆