【问题标题】:Failed to download full rows using Pandas read_excel() for xlsx file [duplicate]无法使用 Pandas read_excel() 为 xlsx 文件下载完整行 [重复]
【发布时间】:2021-04-02 14:11:07
【问题描述】:

该文件应该有数千行。 但是在下面使用它只会返回数据框中的前几行

文件 https://www.hkex.com.hk/eng/services/trading/securities/securitieslists/ListOfSecurities.xlsx

失败的例子

import pandas as pd

url = 'https://www.hkex.com.hk/eng/services/trading/securities/securitieslists/ListOfSecurities.xlsx'
df = pd.read_excel(url, engine='openpyxl', header=2, usecols='A:D', verbose=True)
print(df.shape)
# output - only 5 rows
Reading sheet 0
(5, 4)

工作示例

同一个文件。先下载,在Excel中打开,修改文本并保存(没有改变格式并保留xlsx),然后使用read_excel()从文件中打开

url = 'https://www.hkex.com.hk/eng/services/trading/securities/securitieslists/ListOfSecurities.xlsx'
path = os.path.join(os.path.dirname(__file__), 'download')
wget.download(url, out=path)
file = os.path.join(path, 'ListOfSecurities.xlsx')

# open to edit and then save in Excel

df = pd.read_excel(file, engine='openpyxl', header=2, usecols='A:D', verbose=True)
print(df.shape)
# output
Reading sheet 0
(17490, 4)

【问题讨论】:

  • 这个问题可能是由正在使用的数据引起的。您应该包含一些示例数据,以便帮助人员复制问题。
  • 下载并注意到同样的问题。形状 (5, 4)。数据格式问题。 “Spread Table”和“Board Lot”列问题
  • 但这仍然是有效的 excel 格式。所以在这里寻找解决方案

标签: python excel pandas openpyxl


【解决方案1】:

更新:根据上下文更改代码,xlrd 不可行

import pandas as pd
import os 
import wget

url = 'https://www.hkex.com.hk/eng/services/trading/securities/securitieslists/ListOfSecurities.xlsx'
path = os.path.join(os.path.dirname(__file__), 'download')
wget.download(url, out=path)
filename = os.path.join(path, 'ListOfSecurities.xlsx')

from openpyxl import load_workbook

excel_file = load_workbook(filename)
sheet = excel_file["ListOfSecurities"]
sheet.delete_cols(5,21) # Use only Cols A:D

data = sheet.values
cols = next(data) # Skip row 0
cols = next(data) # Skip row 1
cols = next(data)[0:4] # Cols A:D


df = pd.DataFrame(data, columns=cols)

print(df.shape)

我将 excel 引擎更改为在 pandas 中使用默认引擎 (xlrd),以下代码有效。

import pandas as pd
import os 
import wget

url = 'https://www.hkex.com.hk/eng/services/trading/securities/securitieslists/ListOfSecurities.xlsx'
path = os.path.join(os.path.dirname(__file__), 'download')
wget.download(url, out=path)
filename = os.path.join(path, 'ListOfSecurities.xlsx')

df = pd.read_excel(filename, header=2, usecols='A:D', verbose=True)
print(df.shape)

输出中的一个不一致之处是它显示的行数减少了 4:

Reading sheet 0
(17486, 4)

【讨论】:

  • 谢谢阿西姆。但是我使用的 xlrd 版本不支持 xlsx 文件。 xlrd.biffh.XLRDError:Excel xlsx 文件;不支持。 xlrd == 2.0.1 熊猫 == 1.1.5 stackoverflow.com/questions/65254535/…
  • 您使用的是什么版本的 Pandas?
  • 熊猫 == 1.1.5
  • @memento 将答案更改为使用openpyxl 本身打开文件,然后将其加载到pandas。让我知道这是否有效。
  • 完美运行,谢谢
猜你喜欢
  • 2020-02-12
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 2019-01-27
  • 2020-03-21
  • 2021-05-08
  • 2017-06-08
  • 1970-01-01
相关资源
最近更新 更多