Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

python - Rename columns in PANDAS based on dictionary

I have a dataframe and I would like to rename the columns based on another dataframe that I plan to use as dictionary. For example, what I have as first dataframe is:

          AAA   BBB   CCC   DDD
 index   
  1       1     2     3     4
  2       5     6     7     8

and as a second dataframe that I would like to use as dictionary:

           val1    val2
  index
    1      AAA      A7
    2      BBB      B0
    3      CCC      C3
    4      DDD      D1

What I would like to get as result is the following:

          A7    B0    C3    D1 
 index   
  1       1     2     3     4
  2       5     6     7     8

Initially I thought to reshape the first dataframe to long format, then merge with the dictionary dataframe and then reshape back to wide format. However I think this is quite inefficient, so I would like to use a more efficient way (if one exists). Thank you very much four your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

df.rename has a parameter called columns that accepts dictionaries:

df.rename(columns=dict(zip(df2["val1"], df2["val2"])))

Out:

    A7  B0  C3  D1
0   1   2   3   4
1   5   6   7   8

It returns a new DataFrame. You can either use inplace=True, or assign it back to the original DataFrame.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...