我从csv文件中提取了以下表格。
当我尝试执行以下操作:
我得到了一个错误信息:
当我尝试时:
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能够读取Date
和Time
列并将其转换为datetime
类型,但一直没有成功。以下是我尝试的一些方法:
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
现在,Date
和Time
已经合并到一列中(11/08/2016 14:06:18
)(这正是我想要的),但没有被识别为datetime
。
然后我尝试:
pd.to_datetime(df_2['Date_Time'], format='%d/%m/%Y %H:%M:%S)
我得到了一个错误信息:
File "<ipython-input-31-ace4ed1a0aa9>", 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中手动将日期格式更改为yyyy-mm-dd
,并尝试了相同的事情,但没有任何更好的结果。我觉得这一定是我犯的一个非常基本的错误,我对脚本编写还很新,并希望得到任何帮助。如果我的问题有格式错误,请谅解我,我真的很努力。
SyntaxError: EOL while scanning string literal
错误,因为你在format='%d/%m/%Y %H:%M:%S)
中忘记了一个闭合单引号。 - Khrisdf_2=pd.read_csv(file,parse_dates=[['Date','Time']])
对于您的有限样本数据有效,您可能在df中有一些错误的数据,我建议像第一个片段中那样加载dfdf=pd.read_csv(myfile)
,然后执行df['Date_Time'] = pd.to_datetime(df[['Date','Time']].apply(lambda x: ' '.join(x), axis=1), errors='coerce')
这将强制任何错误的数据转换为“NaT”,您可以使用“dropna”过滤掉这些数据。 - EdChum