How can I change name of arbitrary columns in pandas df using lambda function?
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)
Blaszard
I'm here to gain knowledge and insights on a variety of fields I'm interested in. Specifically, Programming & Software Development (Python and R; no longer use Swift and JavaScript/node.js) Data Science, Machine Learning, AI, & statistics Travel (started in 2016) Language (普通话, français, español, italiano, русский, 한국어) Politics, Economics, and Finance Currently (in 2020), my primary interest is Korean and Russian😈 PS: I'm not a native-English speaker. If you find any errors in my grammar and expressions, don't hesitate to edit it. I'll appreciate it👨🏻💼
Updated on July 18, 2022Comments
-
Blaszard almost 2 years
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 areosx
,centos
,ubunto
,windows
. In this data frame, I want to replace all column names with that column name appended byx
, 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 isosxx
,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 onlambda
function if it's feasible.Thanks.
-
Blaszard almost 11 yearsThanks. I think
os_list
should be better off to only include columns that I want to rename (i.e.os_list = ['osx', 'centos', 'windows']
in this case). -
waitingkuo almost 11 yearsSorry for the mistake, I've removed it from the list.