Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing multiple column names but not all of them - Pandas Python

I would like to know if there is a function to change specific column names but without selecting a specific name or without changing all of them.

I have the code:

df=df.rename(columns = {'nameofacolumn':'newname'}) 

But with it i have to manually change each one of them writing each name. Also to change all of them I have

df = df.columns['name1','name2','etc'] 

I would like to have a function to change columns 1 and 3 without writing their names just stating their location.

like image 938
Antonio López Ruiz Avatar asked Jun 29 '16 13:06

Antonio López Ruiz


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() . columns is for the column name, and index is for the index name.

How do I rename multiple columns?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.

How do I replace values in multiple columns in Pandas?

Pandas replace multiple values in column replace. By using DataFrame. replace() method we will replace multiple values with multiple new strings or text for an individual DataFrame column. This method searches the entire Pandas DataFrame and replaces every specified value.


1 Answers

say you have a dictionary of the new column names and the name of the column they should replace:

df.rename(columns={'old_col':'new_col', 'old_col_2':'new_col_2'}, inplace=True) 

But, if you don't have that, and you only have the indices, you can do this:

column_indices = [1,4,5,6] new_names = ['a','b','c','d'] old_names = df.columns[column_indices] df.rename(columns=dict(zip(old_names, new_names)), inplace=True) 
like image 169
mgoldwasser Avatar answered Sep 23 '22 16:09

mgoldwasser