学习技能、解决问题,我们的目标是 Error: no error
Date,Time,CO2(ppm),CellTemp(c),CellPres(kPa)
10/08/2016,13:21:11,356.89,51.07,99.91
10/08/2016,13:21:12,356.89,51.07,99.91
10/08/2016,13:21:13,356.83,51.07,99.91
我研究了过去的几天,并尝试了不同的方法使 pandas 将“日期”和“时间”列读取为日期时间,但我做不到.这是我尝试过的一些方法:
df = pd.read_csv(myfile)
print(df.dtypes)
我得到:
Date object
Time object
CO2(ppm) object
CellTemp(c) object
CellPres(kPa) object
dtype: object
当我尝试:
df_2 = pd.read_csv(file, parse_dates=[['Date', 'Time']])
print(df_2.dtypes)
我懂了
Date_Time object
CO2(ppm) object
CellTemp(c) object
CellPres(kPa) object
dtype: object
因此,现在“日期和时间”在一栏中(11/08/2016 14:06:18)(我想要的),但未识别为日期时间.
然后,当我尝试:
pd.to_datetime(df_2['Date_Time'], format='%d/%m/%Y %H:%M:%S)
我收到错误消息:
File "", line 1
pd.to_datetime(df_2['Date_Time'],format='%d/%m/%Y %H:%M:%S
SyntaxError: EOL while scanning string literal
当我尝试:
import dateutil.parser
dateutil.parser.parse(df_2['Date_Time'])
我收到(除了其他输出)错误消息:
AttributeError: 'Series' object has no attribute 'read'
我还手动在Excel中将dateformat更改为yyyy-mm-dd,并尝试了相同的操作,但没有任何更好的结果.我认为这一定是我正在做的一个非常基本的错误,我是脚本新手,将不胜感激.如果我的问题确实有格式化错误,请向我道歉.
to_datetime
以将其转换为NaT:
#31.11. does not exist
print (df_2)
Date_Time CO2(ppm) CellTemp(c) CellPres(kPa)
0 10/08/2016 13:21:11 356.89 51.07 99.91
1 10/08/2016 13:21:12 356.89 51.07 99.91
2 31/11/2016 13:21:13 356.83 51.07 99.91
df_2['Date_Time'] = pd.to_datetime(df_2['Date_Time'],
format='%d/%m/%Y %H:%M:%S',
errors='coerce')
print (df_2)
Date_Time CO2(ppm) CellTemp(c) CellPres(kPa)
0 2016-08-10 13:21:11 356.89 51.07 99.91
1 2016-08-10 13:21:12 356.89 51.07 99.91
2 NaT 356.83 51.07 99.91
您还可以通过以下方法检查所有有问题的值:
print (df_2[pd.to_datetime(df_2['Date_Time'],format='%d/%m/%Y %H:%M:%S', errors='coerce').isnull()])
Date_Time CO2(ppm) CellTemp(c) CellPres(kPa)
2 31/11/2016 13:21:13 356.83 51.07 99.91
相关问答