user14269252
user14269252

Reputation: 450

can not change the column name in DataFrame Python

Why I can not change the column name in DataFrame? I tried the following formula in python. Can anyone help me?


df1 = df1.rename(columns={'2019-04-01 00:00:00': 'xx'})

2019-04-01 00:00:00

c
f
g

Upvotes: 0

Views: 519

Answers (3)

Paulo Marques
Paulo Marques

Reputation: 879

Based on my comment.

The column might be in datetime format, not string.

df1 = df1.rename(columns={datetime.strptime('2019-04-01 00:00:00', '%Y-%m-%d %H:%M:%S'): 'xx'})

Upvotes: 1

Feil Narley
Feil Narley

Reputation: 13

The column name is not the exact same thing in this instance so when it is searching for '2019-04-01 00:00:00' it is not found and thus not changed. This could be because one is a string and the other is DateTime. Either make sure you have the type correct or try another method to rename the columns like so:

df1.columns = ['xx']
df1

This will require you to rename all columns so fixing the type is likely the way to go.

Upvotes: 0

lux7
lux7

Reputation: 2150

You can also assign a new name to a column or mulitple columns as follows:

df.columns = ['xx']

or if there are multiple columns

df.columns = ['xx', 'yy']

Upvotes: 0

Related Questions