简体   繁体   中英

Rename the name of the columns of a Pandas Dataframe by the values of another Pandas Dataframe

I would like to rename the columns of my Pandas Dataframe, according to the dictionary located in another Dataframe.

For example, I have the DF1:

在此处输入图像描述

And I would like to rename the name of the df1 columns according to this dictionary:

在此处输入图像描述

My goal is to automatically obtain a dataframe with the following changes:

在此处输入图像描述

PS. I would like to rename the column after the word "fields", to keep the format "field.CHANGE_NAME".

### data for the first dataframe 
data1 = {
"field.customfield_1032": [48,30,28,38],
"field.customfield_1031": ["RSA", "RSB", "RSC", "RSD"],
"field.customfield_1030": ["Thornton", "MacGyver", "Dalton", "Murdoc "]
 }

df1 = pd.DataFrame(data1)
print(df1)


### data for the second dataframe, this is the diccionary with the data
data2 = {"field.ID": ['field.customfield_1030','field.customfield_1031','field.customfield_1032'], 
    "field.Name": ['Surname','ID', 'Age'],}

df2 = pd.DataFrame(data2)
print(df2)

How could I achieve this?

Thank you in advance.

Map the columns to the dict from the combination of df2['field.ID'] & df2['field.Name']

Here is the solution:

df1.columns = df1.columns.map({x: f"field.{y}" for x, y in zip(df2['field.ID'], df2['field.Name'])})
print(df1)
   field.Age field.ID field.Surname
0         48      RSA      Thornton
1         30      RSB      MacGyver
2         28      RSC        Dalton
3         38      RSD       Murdoc 

Let's try

out = df1.rename(columns=dict(df2.values)).add_prefix('field.')
print(out)

   field.Age field.ID field.Surname
0         48      RSA      Thornton
1         30      RSB      MacGyver
2         28      RSC        Dalton
3         38      RSD       Murdoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM