gpt4 book ai didi

python - 无法将对象数据类型转换为日期时间格式

转载 作者:行者123 更新时间:2023-12-01 07:43:57 25 4
gpt4 key购买 nike

我想将列转换为日期时间格式并将日期和时间分开。我已经得到了给定的日期时间转换的解决方案 from the link below:和代码:

df2['date']=pd.to_datetime(df2['date'].astype(str), format='%Y%m%d%H%M',errors='coerce')

但是,每当我尝试查看 df2['date'] 的数据类型时,该列仍然是对象数据类型。当我尝试使用代码将其分离时:

df2['date'], df2['Time'] = df2['date'].dt.normalize(), df['date'].dt.time

它给了我错误:

AttributeError: 'DataFrame' object has no attribute 'dt'

当我打印 df2.columns 时,输出为

MultiIndex(levels=[[u'ALT', u'AW', u'CLG', u'DEWP', u'DIR', u'GUS', u'H', u'L', u'M', u'MAX', u'MIN', u'MW', u'PCP01', u'PCP06', u'PCP24', u'PCPXX', u'SD', u'SKC', u'SLP', u'SPD', u'STP', u'TEMP', u'VSB', u'W', u'date'], [u'F', u'GMT', u'MPH', u'Mb', u'Miles', u'Unnamed: 10_level_1', u'Unnamed: 12_level_1', u'Unnamed: 13_level_1', u'Unnamed: 14_level_1', u'Unnamed: 15_level_1', u'Unnamed: 16_level_1', u'Unnamed: 17_level_1', u'Unnamed: 18_level_1', u'Unnamed: 19_level_1', u'Unnamed: 20_level_1', u'Unnamed: 3_level_1', u'Unnamed: 6_level_1', u'Unnamed: 7_level_1', u'Unnamed: 8_level_1', u'Unnamed: 9_level_1', u'inches']],
labels=[[24, 4, 19, 5, 2, 17, 7, 8, 6, 22, 11, 11, 11, 11, 1, 1, 1, 1, 23, 21, 3, 18, 0, 20, 9, 10, 12, 13, 14, 15, 16], [1, 15, 2, 2, 16, 17, 18, 19, 5, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 0, 3, 20, 3, 0, 0, 20, 20, 20, 20, 20]])

df2.dtypes 的输出为:

date   GMT                     object
DIR Unnamed: 3_level_1 object
SPD MPH float64
GUS MPH int64
CLG Unnamed: 6_level_1 object
SKC Unnamed: 7_level_1 object
L Unnamed: 8_level_1 object
M Unnamed: 9_level_1 object
H Unnamed: 10_level_1 object
VSB Miles float64
MW Unnamed: 12_level_1 object
Unnamed: 13_level_1 object
Unnamed: 14_level_1 object
Unnamed: 15_level_1 object
AW Unnamed: 16_level_1 object
Unnamed: 17_level_1 object
Unnamed: 18_level_1 object
Unnamed: 19_level_1 object
W Unnamed: 20_level_1 object
TEMP F int64
DEWP F object
SLP Mb object
ALT inches object
STP Mb object
MAX F object
MIN F object
PCP01 inches object
PCP06 inches object
PCP24 inches object

PCPXX inches object
SD inches object

最佳答案

列中有MultiIndex,因此对于选择列需要元组:

df2[('date', 'GMT')] = df2[('date', 'GMT')].dt.normalize()
df2[('Time', 'GMT')] = df2[('date', 'GMT')].dt.time

关于python - 无法将对象数据类型转换为日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56557515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com