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.
You can use the rename() method of pandas. DataFrame to change column/index name individually. Specify the original name and the new name in dict like {original name: new name} to columns / index parameter of rename() .
If you want to rename a single column, just pass the single key-value pair in the columns dict parameter. The result will be the same if there is a non-matching mapping in the columns dictionary.
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With