如何使用 lambda 函数更改 pandas df 中任意列的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16770227/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:51:23  来源:igfitidea点击:

How can I change name of arbitrary columns in pandas df using lambda function?

pythonlambdapandasrename

提问by Blaszard

Is there any way to change some column names in pandas dataframe using lambda, but not all? For example, suppose that this data frame has columns whose name are osx, centos, ubunto, windows. In this data frame, I want to replace all column names with that column name appended by x, so in this case, I can rename the column name by:

有什么方法可以使用 来更改 Pandas 数据框中的某些列名lambda,但不是全部?例如,假设此数据框具有名称为osx, centos, ubunto, 的列windows。在这个数据框中,我想用附加的列名替换所有列名x,所以在这种情况下,我可以通过以下方式重命名列名:

df.rename(columns=lambda x: x+'x')

However, if I want to rename all column names other than ubunto, how can I do it? So what I want to get is data frame whose name is osxx, centosx, ubunto, windowsx. Actually, my true data frame has much more columns, so I don't like to write out one-by-one using usual dictionary syntax and instead want to lean on lambdafunction if it's feasible.

但是,如果我想重命名除 之外的所有列名ubunto,我该怎么做?所以我想得到的是名称为osxx, centosx, ubunto, 的数据框windowsx。实际上,我的真实数据框有更多的列,所以我不喜欢使用通常的字典语法一一写出,而是希望在lambda可行的情况下依靠函数。

Thanks.

谢谢。

回答by waitingkuo

A ternary operatormight achieve your goal:

一个三元运营商可能会实现你的目标:

os_list = ['osxx', 'centos', 'windowsx']    
df.rename(columns=lambda x: x+'x' if x in os_list else x)