AirQualityUCI.csv
。以下是 10 行的示例,包括第一行字段名称:
Date;Time;CO(GT);PT08.S1(CO);NMHC(GT);C6H6(GT);PT08.S2(NMHC);NOx(GT);PT08.S3(NOx);NO2(GT);PT08.S4(NO2);PT08.S5(O3);T;RH;AH;;
10/03/2004;18.00.00;2,6;1360;150;11,9;1046;166;1056;113;1692;1268;13,6;48,9;0,7578;;
10/03/2004;19.00.00;2;1292;112;9,4;955;103;1174;92;1559;972;13,3;47,7;0,7255;;
10/03/2004;20.00.00;2,2;1402;88;9,0;939;131;1140;114;1555;1074;11,9;54,0;0,7502;;
10/03/2004;21.00.00;2,2;1376;80;9,2;948;172;1092;122;1584;1203;11,0;60,0;0,7867;;
31/03/2005;06.00.00;0,9;1068;-200;6,1;816;191;681;80;1264;1011;12,6;71,5;1,0380;;
31/03/2005;07.00.00;4,0;1531;-200;23,6;1394;673;407;133;1860;1683;12,7;69,6;1,0206;;
31/03/2005;08.00.00;4,1;1184;-200;10,9;1012;547;567;170;1397;1341;16,8;51,6;0,9818;;
31/03/2005;09.00.00;1,9;1064;-200;6,8;848;275;692;139;1212;1014;20,3;40,1;0,9439;;
31/03/2005;10.00.00;1,3;996;-200;4,9;759;200;773;124;1119;751;21,0;37,3;0,9139;;
摄取代码改编自here,其中没有以下
date_format
规范:
import pandas as pd
df = pd.read_csv(
"AirQualityUCI.csv", sep=';', decimal=',',
date_format='%d/%m/%Y',
parse_dates=[["Date", "Time"]],
na_values=[-200],
usecols=["Date", "Time", "CO(GT)", "T", "RH", "AH"]
).rename(
columns={
"CO(GT)": "co",
"Date_Time": "tstamp",
"T": "temp_c",
"RH": "rel_hum",
"AH": "abs_hum",
}
).set_index("tstamp")
使用
date_format
选项消除了之前的警告:
c:\cygwin64\home\User.Name\Some.Path\trygroupby.py:28:
UserWarning: Could not infer format, so each element will be
parsed individually, falling back to `dateutil`. To ensure parsing
is consistent and as-expected, please specify a format.
df = pd.read_csv(
尽管如此,日期/时间索引仍然只是一个字符串,就像使用
date_format
: 之前一样
>>> df.index.day_name()
AttributeError: 'Index' object has no attribute 'day_name'
>>> type(df.index.min())
str
我做错了什么
date_format
?
注释
[1] 这里是主机网页。
AirQualityUCI.csv
的最后几行只包含空字段,已被我删除。
问题出在输入数据的
Time
字段。通过向 read_csv
的 date_format
选项添加时间格式解决了这个问题:date_format='%d/%m/%Y %H.%M.%S'
。
感谢@Barmar在评论中指出这一点。