如何将Pandas中的日期列正确读取为日期类型?
问题:无法将DataFrame的Date列转换为datetime类型
我编写了如下代码,可下载电子表格并将工作表加载为DataFrame,但Date列未按预期转换为日期类型:
import requests import pandas as pd def get_BH_spreadsheet(URLS, SPREADSHEET_NAME): resp = requests.get(URLS) output = open(SPREADSHEET_NAME, 'wb') output.write(resp.content) output.close() df_NA_RIG_COUNT = pd.read_excel(open(SPREADSHEET_NAME, 'rb'), sheet_name='US Oil & Gas Split', index_col=None,header = 'infer', skiprows=6) df_NA_RIG_COUNT['Date'] = pd.to_datetime(df_NA_RIG_COUNT['Date'] ) return df_NA_RIG_COUNT
示例调用:
get_BH_spreadsheet('https://rigcount.bakerhughes.comstatic-files/027e0bcc-86ec-407b-9029-b5bd3bf1982b', 'North America Rotary Rig Count - Jan 2000 - Current.xlsx')
执行后Date列仍未转为datetime类型,即使单独执行df_NA_RIG_COUNT['Date'] = pd.to_datetime(df_NA_RIG_COUNT['Date'])也无效,该如何解决?
解决方案
试试以下几种方法:
读取Excel时直接解析日期列
无需后续手动转换,直接在pd.read_excel中添加parse_dates=['Date']参数,让pandas在读取阶段自动处理日期:df_NA_RIG_COUNT = pd.read_excel( open(SPREADSHEET_NAME, 'rb'), sheet_name='US Oil & Gas Split', index_col=None, header='infer', skiprows=6, parse_dates=['Date'] # 新增参数 )明确指定日期格式,避免自动解析偏差
如果Date列是特殊格式(比如非ISO标准),在pd.to_datetime中用format参数锁定格式,同时用errors='coerce'将无法解析的内容转为NaT方便排查:# 假设日期格式为MM/DD/YYYY,可根据实际情况调整格式字符串 df_NA_RIG_COUNT['Date'] = pd.to_datetime(df_NA_RIG_COUNT['Date'], format='%m/%d/%Y', errors='coerce')检查原始数据是否存在异常
先打印Date列的前几行和数据类型,确认是否有非日期内容(比如空值、备注文字):print(df_NA_RIG_COUNT['Date'].head()) print(df_NA_RIG_COUNT['Date'].dtype)若存在异常值,先过滤或清洗后再执行日期转换。
处理Excel数值型日期
部分Excel文件会把日期存储为序列号(以1899-12-30为起始点),可通过origin参数指定起始日期来转换:df_NA_RIG_COUNT['Date'] = pd.to_datetime(df_NA_RIG_COUNT['Date'], origin='1899-12-30', errors='coerce')
内容的提问来源于stack exchange,提问作者prashanth manohar
相关产品推荐
相关产品推荐

