Skip to content
Advertisement

How to rename columns by position?

from pandas import DataFrame
df = DataFrame({
  'A' : [1, 2, 3]
  , 'B' : [3, 2, 1]
})
print(df.rename(columns={'A': 'a', 'B': 'b'}))

I know that I can rename columns like the above.

But sometimes, I just what to rename columns by position so that I don’t have to specify the old names.

df.rename(columns=['a', 'b']))
df.rename(columns={0: 'a', 1: 'b'})

I tried the above. But none of them work. Could anybody show me a concise way to rename without specifying original names?

I looking for a way with minimal code. Ideal, this should and could have been supported by the current function interface of rename(). Using a for-loop or something to create a dictionary with the old column names could be a solution but not preferred.

Advertisement

Answer

You might assign directly to pandas.DataFrame.columns i.e.

import pandas as pd
df = pd.DataFrame({'A':[1, 2, 3],'B':[3, 2, 1]})
df.columns = ["X","Y"]
print(df)

output

   X  Y
0  1  3
1  2  2
2  3  1
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement