Mario Arend
Mario Arend

Reputation: 479

Rename all columns names by position

I am trying to rename the columns of a DataFrame that has more than one hundred columns by their position (x1, x2, x3, etc.). I created the code below, but it is very inefficient. Is there a faster and better way of doing this in Pandas-Python?

for i, column_name in enumerate(df.columns.values):
     df.rename(columns={ df.columns[i]: "x" + str(i+1) }, inplace=True)

Upvotes: 0

Views: 586

Answers (2)

avloss
avloss

Reputation: 2626

You can directly assign to "df.columns".

df.columns = [f'x{i+1}' for i in range(len(df.columns))]

Upvotes: 3

BENY
BENY

Reputation: 323226

Let us do

df.columns=np.arange(df.shape[1])+1
df=df.add_prefix('x')

Upvotes: 1

Related Questions