简体   繁体   中英

How to replace df column names with df1's

I have 2 dfs with an identical amount of columns, however, they have 2 different naming conventions because I got the data from 2 different places. I want df_cont to have the same column names as df1.

I know I could do it like this:

df_cont.rename({'bitcoin':'BTC'}, axis='columns')

But this would take ages because of the many columns I have.

I tried to do:

df_cont = df_cont.rename(columns = df1.columns, inplace = True)

But this throws an error. Based on pandas documentation it looks like it wants me to give the index labels, but the 2 df's have different time-series lengths.


df1
    btc  eth  ltc 


df_cont
    bitcoin ethereum litcoin

expected:

df_cont
    btc   eth  ltc

Set columns names by df1.columns :

df_cont.columns = df1.columns

Sample :

df1 = pd.DataFrame([[1,2,3]], columns=['btc', 'eth', 'ltc'])
print (df1)
   btc  eth  ltc
0    1    2    3

df_cont = pd.DataFrame([[11,22,33]], columns=['bitcoin', 'ethereum', 'litcoin'])   
print (df_cont)
   bitcoin  ethereum  litcoin
0       11        22       33

df_cont.columns = df1.columns
print (df_cont)
   btc  eth  ltc
0   11   22   33

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