无法使用read_excel从熊猫的xlsx文件读取日期列?

时间:2019-10-15 16:48:55

标签: python excel pandas date datetime

我在Excel中有一些格式为日期的单元格(请参见下文):

Format of cells in question is Date

我无法读取它们(它们是NaN),所以当我从熊猫to_datetime方法中读取它们时,我使用了转换器尝试将它们转换为read_excel

   cols_A8_J2007[i] = pd.read_excel(
                      i, 
                     ('sheet'+str(j)), 
                     headers = 1, skiprows = 6, nrows=2000, 
                     usecols = 'A:J', 
                     converters = {
                       'Expired': lambda x: pd.to_datetime(x, errors='coerce') , 
                   'Valid Until': lambda x: pd.to_datetime(x, errors='coerce')})

这导致它们全部都以NaT的形式加载。

因此,在查阅了文档之后,我以这种方式进行了尝试:

    cols_A8_J2007[i] = pd.read_excel(i, ('sheet'+str(j)), headers = 1, parse_dates=True, skiprows = 6, nrows=2000, usecols = 'A:J' )

这又是NaN的结果。

最后,我改为这样尝试,并且再次获得NaN

    cols_A8_J2007[i] = pd.read_excel(i, ('sheet'+str(j)), headers = 1, parse_dates=True, date_parser=lambda x: pd.to_datetime(x, errors='coerce'), skiprows = 6, nrows=2000, usecols = 'A:J' )

上面的方法不起作用,因为它试图基于索引进行解析(请参见下面的注释)。

cols_A8_J2007[i] = pd.read_excel(i, ('sheet'+str(j)), headers = 1, parse_dates=['Expired', 'Valid Until'], skiprows = 6, nrows=2000, usecols = 'A:J' )
cols_A8_J2007[i] = pd.read_excel(i, ('sheet'+str(j)), headers = 1, parse_dates=['Expired', 'Valid Until'], skiprows = 6, nrows=2000, usecols = 'A:J' )
cols_A8_J2007[i] = pd.read_excel(i, ('sheet'+str(j)), headers = 1, parse_dates=['Expired', 'Valid Until'], dateparser=lambda x: pd.to_datetime(x, errors='coerce'), skiprows = 6, nrows=2000, usecols = 'A:J' )

这两个都导致NaT(不是时间?)

阅读日期还需要做什么?我意识到没有附加时间,但是Excel stores dates and times的方式无关紧要,因为时间存储为小数。

for i in glob.iglob(((str(xls_folder) + '\somesheets*.xlsx'))):
    cols_A8_J2007[i] = pd.read_excel(i, ('sheet'+str(j)), headers = 1, skiprows = 6, nrows=2000, usecols = 'A:J', converters = {'Expired': lambda x: pd.to_datetime(x, errors='coerce') , 'Valid Until': lambda x: pd.to_datetime(x, errors='coerce')})

for w in cols_A8_J2007:
    print(cols_A8_J2007[w].dtypes)

Type                      object
Currency                  object
Initial Credit           float64
Credits                  float64
Debits                   float64
Balance                  float64
Reserved                   int64
Valid Until       datetime64[ns] <-  <- These I believe are what you are looking for..
Expired           datetime64[ns] <- These I believe are what you are looking for..
dtype: object

如果这对我有帮助的话,也是我的版本:

pd.versions()
INSTALLED VERSIONS
------------------
commit: None
python: 3.7.3.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 158 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.24.2
pytest: 4.5.0
pip: 19.1.1
setuptools: 41.0.1
Cython: 0.29.8
numpy: 1.16.4
scipy: 1.2.1
pyarrow: None
xarray: None
IPython: 7.5.0
sphinx: 2.0.1
patsy: 0.5.1
dateutil: 2.8.0
pytz: 2019.1
blosc: None
bottleneck: 1.2.1
tables: 3.5.1
numexpr: 2.6.9
feather: None
matplotlib: 3.0.3
openpyxl: 2.6.2
xlrd: 1.2.0
xlwt: 1.3.0
xlsxwriter: 1.1.8
lxml.etree: 4.3.3
bs4: 4.7.1
html5lib: 1.0.1
sqlalchemy: 1.3.3
pymysql: None
psycopg2: None
jinja2: 2.10.1
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None
gcsfs: None

1 个答案:

答案 0 :(得分:0)

确定问题是我需要使用pd.isnull检查值是否为空。该文件对我来说有太多的空值,无法在结果集中看到它们。在这里找到答案:how to test if a variable is pd.NaT?

me_df = pd.read_excel(i, ('iCareAcctListing'+str(j)), headers = 1, skiprows = 6, nrows=2000, usecols = 'A:J', converters = {'Expired': lambda x: pd.to_datetime(x, errors='coerce') , 'Valid Until': lambda x: pd.to_datetime(x, errors='coerce')})

# Ran this and ended up with just the dates that were 
# filled in with actual values.
#
# There were so many nulls before and after that I couldn't see any of them in the dataset!
me_df[pd.isnull(me_df['Valid Until']) != True]