简体   繁体   English

无法更改 DataFrame Python 中的列名

[英]can not change the column name in DataFrame Python

Why I can not change the column name in DataFrame?为什么我不能更改 DataFrame 中的列名? I tried the following formula in python.我在 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

Based on my comment.根据我的评论。

The column might be in datetime format, not string .该列可能是datetime格式,而不是string

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

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']

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.在这种情况下,列名并不完全相同,因此当它搜索“2019-04-01 00:00:00”时,没有找到它,因此没有更改。 This could be because one is a string and the other is DateTime.这可能是因为一个是字符串,另一个是 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.这将要求您重命名所有列,因此修复类型可能是 go 的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM