首页 > 解决方案 > 使用 XLRD 从 excel 表中的列中读取 int 值

问题描述

我在一个带有逗号分隔值的 Excel 工作簿中有一个单元格。

列的 CSV 值

此单元格可以具有以下模式的值。

0123123, 345

XLRD我想使用or将它们提取为整数列表pandas.read_excel

我尝试使用带有以下代码段的 xlrd。

book = open_workbook(args.path)
dep_cms = book.sheet_by_index(1)
for row_index in range(1, dep_cms.nrows)
    excelList = []
    excelList.extend([x.strip() for x in dep_cms.cell(row_index, 8).value.split(',')])

我什至尝试过熊猫

excel_frame = read_excel(args.path, sheet_name=2, skiprows=1, verbose=True, na_filter=False)
data_need = excel_frame['Dependent CMS IDS'].tolist()
print(data_need)

但得到的列表索引超出范围。

Reading sheet 2
Traceback (most recent call last):
  File "ExcelCellCSVRead.py", line 25, in <module>
    excel_frame = read_excel(args.path, sheet_name=2, skiprows=1, verbose=True, na_filter=False)
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 311, in read_excel
    return io.parse(
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 868, in parse
    return self._reader.parse(
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 441, in parse
    sheet = self.get_sheet_by_index(asheetname)
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_xlrd.py", line 46, in get_sheet_by_index
    return self.book.sheet_by_index(index)
  File "C:\Users\Kris\AppData\Local\Programs\Python\Python38-32\lib\site-packages\xlrd\book.py", line 466, in sheet_by_index
    return self._sheet_list[sheetx] or self.get_sheet(sheetx)
IndexError: list index out of range

它不适用于单元格中的单个值(例如,只有 0 或某个值,如 123)。它正在输出AttributeError: 'float' object has no attribute 'split'

它仅在我有逗号分隔值时才有效,并将它们转换为字符串列表,如['123', '345']. 我猜分裂条件是罪魁祸首。

如何使用 XLRD 或 pandas 将此单元格的值提取到整数列表中

问候

标签: python-3.xexcelpandaslistxlrd

解决方案


导入期间无法将逗号分隔值 (CSV) 与 Excel 进行比较。

而不是使用read_excel你可以使用read_csv.

以下是您的代码在应用后的样子的代码片段read_csv

Import Pandas as pd
df = pd.read_csv("your file name.csv")
data_need = df["Column_name"].tolist()

推荐阅读