JavaScript
x
7
1
from pandas import DataFrame
2
df = DataFrame({
3
'A' : [1, 2, 3]
4
, 'B' : [3, 2, 1]
5
})
6
print(df.rename(columns={'A': 'a', 'B': 'b'}))
7
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.
JavaScript
1
3
1
df.rename(columns=['a', 'b']))
2
df.rename(columns={0: 'a', 1: 'b'})
3
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.
JavaScript
1
5
1
import pandas as pd
2
df = pd.DataFrame({'A':[1, 2, 3],'B':[3, 2, 1]})
3
df.columns = ["X","Y"]
4
print(df)
5
output
JavaScript
1
5
1
X Y
2
0 1 3
3
1 2 2
4
2 3 1
5