Reputation: 661
I am trying to rename a column by position in a pandas dataframe.
I tried:
df.rename(columns={ df.columns[0]: "Line Items" }, inplace=True) #replace name
But this code replaces all columns which has have the same name as column[0] with "Line Items" irrespective of their positions.
Upvotes: 1
Views: 1939
Reputation: 323226
Let us convert to series
then change the value by .iloc
and assign it back
s = df.columns.to_series()
s.iloc[0] = 'something'
df.columns = s
Upvotes: 3
Reputation: 59519
You can assign the columns in a list comprehension with basic logic
import pandas as pd
df = pd.DataFrame(columns=list('AABCDA'))
df.columns = ["Line Items" if i == 0 else x for i,x in enumerate(df.columns)]
print(df)
#Empty DataFrame
#Columns: [Line Items, A, B, C, D, A]
#Index: []
Upvotes: 3