我想将列转换为DateTime格式并分隔日期和时间。我已经有了给定日期时间转换的解决方案 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
答案 0 :(得分:1)
列中有MultiIndex
,因此对于选择列,需要元组:
df2[('date', 'GMT')] = df2[('date', 'GMT')].dt.normalize()
df2[('Time', 'GMT')] = df2[('date', 'GMT')].dt.time