[英]Rename the name of the columns of a Pandas Dataframe by the values of another Pandas Dataframe
根據位於另一個 Dataframe 中的字典,我想重命名我的 Pandas Dataframe 的列。
例如,我有 DF1:
我想根據這本字典重命名 df1 列的名稱:
我的目標是通過以下更改自動獲得 dataframe:
PS。 我想在單詞“fields”之后重命名該列,以保持格式“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)
我怎么能做到這一點?
先感謝您。
Map df2['field.ID']
& df2['field.Name']
組合的字典列
這是解決方案:
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
我們試試看
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.