python - 处理 pandas.datetime 类型时出现消息 "Exception ignored"

标签 python python-3.x pandas exception warnings

我有一个 xlsx 文件,其中有一列包含格式为“01.01.1900 09:01:25”的日期。该文件受密码保护,因此我通过 win32com.client 库将其转换为数据帧。

这是代码:

import pandas as pd
import win32com.client

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.DisplayAlerts = False
xlwb = xlApp.Workbooks.Open(File, False, True, None, " ") #Open Workbook password " "
xlws = xlwb.Sheets("Sheet 1") #Open Sheet 1        

#Get table dimensions 
LastRow = xlws.Range("A1").CurrentRegion.Rows.Count
LastColumn = xlws.Range("A1").CurrentRegion.Columns.Count
header=list((xlws.Range(xlws.Cells(1, 1), xlws.Cells(1, LastColumn)).Value)[0])
content = list(xlws.Range(xlws.Cells(2, 1), xlws.Cells(LastRow, LastColumn)).Value)
#Get the dataframe
df=pd.DataFrame(data=content, columns=header)
print (df)

我检查过导入的 dtype 是否已自动且正确地分配给该列的 datetime64。问题是,每当我尝试对该列的任何值执行任何操作(只需打印它或比较它)时,我都会收到一条消息:

  File "pandas\_libs\tslibs\timezones.pyx", line 227, in pandas._libs.tslibs.timezones.get_dst_info

AttributeError: 'NoneType' object has no attribute 'total_seconds'

Exception ignored in: 'pandas._libs.tslib._localize_tso'
Traceback (most recent call last):
  File "pandas\_libs\tslibs\timezones.pyx", line 227, in pandas._libs.tslibs.timezones.get_dst_info
AttributeError: 'NoneType' object has no attribute 'total_seconds'
Traceback (most recent call last):

尽管如此,代码运行得很好,但警告消息让我很恼火。

我可以对数据类型做些什么来避免该警告吗?

最佳答案

这样打开excel,content变量是一个元组列表。

查看这些元组,有一个 TimeZoneInfo 本地化某种时区中的所有日期,在我的例子中为“GMT 标准时间”。

因此,一旦转换为数据帧,执行df.dtypes时,结果不仅是“datetime64”,而且是“datetime64 (UTC+0:00) Dublin, Edimburg, ...”

此时区设置仅在通过 win32com.client 打开 Excel 文件时发生。如果您删除了密码,则可以使用 pandas.read_excel 打开它,并发现没有为这些日期时间设置时区,并且不会出现上述警告。

不知道发生这种情况的确切原因,但我对原始示例有一个解决方案。将 tz 数据库识别的时区设置为 "UTC" 或简单地 None 时,警告就会消失。像这样的东西:

df["col_name"]=df["col_name"].dt.tz_convert(None)

关于python - 处理 pandas.datetime 类型时出现消息 "Exception ignored",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827582/

相关文章:

python - 如何在数据框中查找相似的术语并将其分组以求和它们的值?

python - Pandas:将宽数据框 reshape 为多索引长数据框

numpy - 具有多索引到Numpy矩阵的Pandas DataFrame

python - Pandas,来自 2 个 DF 的两列的总和值

python - 在 virtualenv 中使用 Python 3

python - 如何停止并重复某个功能?

python - 尝试用 0 替换负数时 numpy 数组中的 TypeError

python - 如果字典中的多个键设置为“无”,如何检查它们是否存在?

python - 使用 Python 的 Notepad++ 折叠线

python - 对 Python 中的列表列表进行简洁快速的 zip 操作?