Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 403
Blaszard Avatar asked May 27 '13 09:05

Blaszard


People also ask

How do I change a specific column name in Pandas?

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() .

How do you rename a specific column in Python?

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.


1 Answers

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)
like image 192
waitingkuo Avatar answered Oct 25 '22 08:10

waitingkuo