How to change the name of arbitrary columns in pandas df using lambda function?

Is there a way to change column names in pandas dataframe using lambda , but not all? Suppose, for example, that this data frame has columns named osx , centos , ubunto , windows . In this data frame, I want to replace all column names with this column name added by x , so in this case I can rename the column name:

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

However, if I want to rename all column names except ubunto , how can I do this? So, I want to get a data frame whose name is osxx , centosx , ubunto , windowsx . In fact, my true data frame has a lot more columns, so I don't like to write one by one using the usual dictionary syntax and instead want to rely on the lambda function if possible.

Thanks.

+6
source share
1 answer

A ternary operator can achieve your goal:

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

Source: https://habr.com/ru/post/945920/


All Articles