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

戏子无情 提交于 2020-06-25 09:49:04

问题


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:

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 lambda function if it's feasible.

Thanks.


回答1:


A ternary operator might achieve your goal:

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


来源:https://stackoverflow.com/questions/16770227/how-can-i-change-name-of-arbitrary-columns-in-pandas-df-using-lambda-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!