【发布时间】:2020-08-15 22:31:44
【问题描述】:
我在 Excel 工作簿中有一个以逗号分隔值的单元格。
此单元格可以具有以下模式的值。
0 或 123 或 123, 345。
我想使用XLRD 或pandas.read_excel 将它们提取为整数列表。
我已经尝试使用带有以下 sn-p 的 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 将这个单元格的值提取到一个整数列表?
问候
【问题讨论】:
-
对于
read_excelskiprows必须是类似列表的。也许这个link 可以提供帮助。 -
另外,
sheet_name=2表示third sheet,请确保这是您想要的,或者直接使用工作表名称。
标签: python-3.x excel pandas list xlrd