问题
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