如何在 python 中将日期时间列名称重命名为字符串格式?
How to rename datetime column name to string format in python?
我有一个数据集,其列名采用日期时间格式:
我想将他们的名字更改为 2014-01-01 00:00:00 > Jan-14 等等。
operations.columns = pd.to_datetime(operations.columns).to_period('M')
上面的代码给我以下错误:
ParserError:未知字符串格式:飞机名称
我该如何解决这个问题?
这是更改它的一种方法。检查列类型是否为日期时间,否则重新格式化,保持原样
import datetime
operations.columns = [col.strftime('%M %d')
if (isinstance(col, datetime.date) )
else col
for col in operations.columns]
您可以将列名解析为日期时间(并将格式解析为所需的格式),然后仅使用转换成功的那些元素(否则使用旧元素)。例如:
import pandas as pd
df = pd.DataFrame({'a': [1, 1, 1], 'b': [2, 2, 2], '2021-02-22 00:00:00': [3, 3, 3]})
newnames = pd.to_datetime(df.columns, errors='coerce').strftime("%b-%d")
df.columns = newnames.where(~newnames.isnull(), df.columns)
df
a b Feb-22
0 1 2 3
1 1 2 3
2 1 2 3
我有一个数据集,其列名采用日期时间格式:
我想将他们的名字更改为 2014-01-01 00:00:00 > Jan-14 等等。
operations.columns = pd.to_datetime(operations.columns).to_period('M')
上面的代码给我以下错误:
ParserError:未知字符串格式:飞机名称 我该如何解决这个问题?
这是更改它的一种方法。检查列类型是否为日期时间,否则重新格式化,保持原样
import datetime
operations.columns = [col.strftime('%M %d')
if (isinstance(col, datetime.date) )
else col
for col in operations.columns]
您可以将列名解析为日期时间(并将格式解析为所需的格式),然后仅使用转换成功的那些元素(否则使用旧元素)。例如:
import pandas as pd
df = pd.DataFrame({'a': [1, 1, 1], 'b': [2, 2, 2], '2021-02-22 00:00:00': [3, 3, 3]})
newnames = pd.to_datetime(df.columns, errors='coerce').strftime("%b-%d")
df.columns = newnames.where(~newnames.isnull(), df.columns)
df
a b Feb-22
0 1 2 3
1 1 2 3
2 1 2 3