Renaming columns after merging data in Pandas

Viewed 1901

I have two Pandas series which I merged using the following code:

HS4_Tariffs_16=pd.concat([df_tariff_HS4_16_PT,df_tariff_HS4_16_MFN],axis=1)

If you are wondering why I used concat in place of merge, the error 'Series' object has no attribute 'merge' showed up when I used merge. So anyway, I merged the two series using concat which resulted in a dataframe. Thereafter, I reset the index using the code:

HS4_Tariffs_16.reset_index()

Now the real problem cropped up when I tried to rename a column using the code:

HS4_Tariffs_16=HS4_Tariffs_16.rename(columns={'ProductCode':'HSCode'})

Instead of renaming the column, it converted the column to an index. The output was someting like this:

      Preferential tariff for APTA countries    MFN duties (Applied)
ProductCode         
101     0.3     0.3
102     0.3     0.3
103     0.3     0.3
104     0.3     0.3
105     0.3     0.3
...     ...     ...
9702    0.1     0.1
9703    0.1     0.1
9704    0.0     0.0
9705    0.1     0.1
9706    0.1     0.1

1224 rows × 2 columns

Could you tell me which part of the code I need to correct if the final result that I want is a dataframe with the column named 'ProductCode' renamed as 'HSCode'.

2 Answers

The following might work without having to reset the index. It could be setting it as index as you're renaming the frame as itself when you rename the column and Pandas is weird like that sometimes!

HS4_Tariffs_16.rename(columns={'ProductCode':'HSCode'}, inplace=True)

You can use the rename_axis method to change the name of index columns. This avoids changing the data and adding a potentially unnecessary new index column.

HS4_Tariffs_16.rename_axis(index={'ProductCode':'HSCode'}, inplace=True)

You can also do this in one step using round brackets for cleaner code:

HS4_Tariffs_16 = (
    pd.concat([df_tariff_HS4_16_PT, df_tariff_HS4_16_MFN], axis=1)
    .rename_axis(index={'ProductCode':'HSCode'})
)
Related