使用pandas read_csv指定date_format仍未解析日期时间字段问题
问题原因分析
你设置的date_format='%d/%m/%Y'只匹配了Date字段的格式,但当用parse_dates合并Date和Time字段时,pandas会先将两列拼接成包含日期+时间的完整字符串(比如"10/03/2004 18:00:00"),此时你的格式字符串缺少时间部分的匹配规则,导致pandas无法将拼接后的字符串正确解析为datetime类型,最终合并后的字段(或索引)仍为字符串类型,调用day_name()自然会报错。
解决方案
方案1:指定包含时间部分的完整格式字符串
假设你的Time字段格式为%H:%M:%S(比如18:00:00),将date_format设置为包含日期和时间的完整格式,让pandas能正确解析拼接后的字符串:
import pandas as pd df = pd.read_csv( 'AirQualityUCI.csv', sep=';', decimal=',', parse_dates=[['Date', 'Time']], # 合并Date和Time为一列 date_format='%d/%m/%Y %H:%M:%S', # 匹配完整的日期+时间格式 index_col='Date_Time' # 将合并后的列设为索引 ) # 验证索引类型和功能 print(type(df.index[0])) # 输出应为 <class 'pandas._libs.tslibs.timestamps.Timestamp'> print(df.index.day_name()) # 正常输出星期名称
方案2:先读取再手动合并转换
如果不确定时间字段的具体格式,或者不想写完整格式字符串,可以先读取数据,再手动合并Date和Time并转换为datetime类型:
import pandas as pd df = pd.read_csv( 'AirQualityUCI.csv', sep=';', decimal=',' ) # 合并Date和Time并转换为datetime df['datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'], format='%d/%m/%Y %H:%M:%S') df.set_index('datetime', inplace=True) # 验证 print(type(df.index[0])) print(df.index.day_name())
额外注意
如果你的Time字段格式不是%H:%M:%S,需要根据实际格式调整date_format中的时间部分(比如如果是%H:%M,就写成%d/%m/%Y %H:%M)。
内容的提问来源于stack exchange,提问作者user2153235
相关产品推荐
相关产品推荐

