Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename columns based on another DataFrame

I have a DataFrame dataframe1 with columns ['A', 'B', 'C', 'D'].

I have another DataFrame dataframe2 as below:

Old_Names New_Names
A    1st
B    2nd
C    3rd
D    4th

How do I use dataframe2 to change the column names in dataframe1 to ['1st', '2nd', '3rd', '4th']?

like image 790
As3adTintin Avatar asked Sep 10 '15 14:09

As3adTintin


People also ask

Can a column be renamed in DataFrame?

One way of renaming the columns in a Pandas Dataframe is by using the rename() function. This method is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed.

How do I get column names from a DataFrame in python?

You can get the column names from pandas DataFrame using df. columns. values , and pass this to python list() function to get it as list, once you have the data you can print it using print() statement.

How do I rename a column in a DataFrame in R?

Rename Column in R Dataframe using rename() rename() is the method available in the dplyr package, which is used to change the particular column name present in the data frame. The operator – %>% is used to load the renamed column names to the data frame. At a time we can change single or multiple column names.


2 Answers

You can use the rename function:

dataframe1.rename(columns=dataframe2.set_index('Old_Names')['New_Names'], inplace=True)

The columns argument can be dict-like or a function, and in this case a Series representing the names mapping is used.

like image 198
YS-L Avatar answered Oct 05 '22 00:10

YS-L


You can simply use dataframe1.columns:

dataframe1.columns=dataframe2.columns.values
like image 35
Hajar Homayouni Avatar answered Oct 05 '22 02:10

Hajar Homayouni