python - 使用 zip 时出现输入错误

标签 python excel pandas openpyxl

我正在尝试使用 python 脚本将多个 xlsx 文件中的特定行添加到列表中。我尝试添加的行是第 4 列(E 列)的单元格值减去第 1 列(B 列)的单元格值不等于 0 的行。我的 xlsx 文件如下所示:

   A    B    C    D    E    F    G    H
1 A10   2        A10   2             AB
2 A105  1        A105  2             AB    

因此,对于下面的代码,我希望将第二行添加到打开的列表数字中,因为2-1的总和不为0。然后我想通过将它们添加到列列表中来对它们进行排序,然后将它们放入进入一个新列表,主列表,其中所有内容都已排序。这是我的代码:

import logging
import pandas as pd
from openpyxl import Workbook, load_workbook
import glob
from openpyxl.utils.dataframe import dataframe_to_rows

numbers = []
rapp = r"C:\Myfolder"
files = glob.glob(rapp)
for file in files:
    df = pd.read_excel(file)
    numbers = df.iloc[:, 4], df.iloc[:,1][df.iloc[:, 4] - df.iloc[:,1] != 0].tolist()
excel_input = load_workbook(excelfile)
ws = excel_input.active
for r in dataframe_to_rows(df, index=True, header=True):
    ws.append(r)
else:
    pass

col1 = []
col2 = []
col4 = []
col5 = []
col7 = []
col8 = []

mainlist = []
try:
    for row in numbers:
        col1.append(ws.cell(row=row, column=1).value)
        col2.append(ws.cell(row=row, column=2).value)
        col4.append(ws.cell(row=row, column=4).value)
        col5.append(ws.cell(row=row, column=5).value)
        col7.append(ws.cell(row=row, column=7).value)
        col8.append(ws.cell(row=row, column=8).value)
except AttributeError:
    logging.error('Something is wrong')
finally:
    for col1, col2, col4, col5, col7, col8 in zip: #Error
        mainlist.append(col1, col2, col4, col5, col7, col8)
return mainlist

这是错误:

Traceback:
    for col1, col2, col4, col5, col7, col8 in zip 
TypeError: 'type' object is not iterable.

这给了我错误。 我知道这里有一些错误,很抱歉,但这是我能想到的最好的方法来解决我的任务。有人可以帮助我吗?我将不胜感激!我是Python新手。使用 Python 3.4.1。

最佳答案

您的问题是您对 zip 的使用,这是一个您从 undefined variable 。但是,因为 zip()built-in function它返回 zip-class object ,这让事情变得扑朔迷离。

for col1, col2, col4, col5, col7, col8 in zip: 试图找到一个名为 zip 的迭代器,它有 6 个子组件。由于 zip() 是内置函数,Python 将此行读取为“迭代 zip 类型”,但类型不可迭代,因此您会收到相应的错误。如果您选择了非内置的内容,您将收到 NameError

您的示例有点不清楚,但我相信您可以使用下面的 finally block 来修复它( proof of concept ):

finally:
    columns = zip(col1, col2, col4, col5, col7, col8)
    for column in columns: 
        mainlist.append(column)

关于python - 使用 zip 时出现输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45570200/

相关文章:

python - 如何打印数学符号

python - forloop.counter 表示 for 标签已经循环了多少次

vba - 对于导致类型不匹配的每个循环条件

python - Google Colaboratory 上出现 "lxml not found, please install it"错误

python - Pandas 重新排列多索引系列

python - 如何在类型提示中指定 pandas 系列元素的类型?

python - Django 渲染和重定向 URL

python - Airflow - 得到一个意外的关键字参数 'conf'

c# - 有没有办法从 ExcelWorkBook 中获取 byte[] 而无需先将其保存到磁盘

excel - 类似于 WEBSERVICE 但适用于 https 的 Excel 函数