首页 > 解决方案 > 在' 需要字符串作为左操作数,而不是元组

问题描述

我有带有美国各州的多张工作表的excel模板(MTHLY-CA...etc)

在此处输入图像描述

我还有一个包含列的数据框StateIDpremiumtest

在此处输入图像描述

这个想法是遍历工作表名称并将其与数据框中的列 StateID 进行比较。如果状态匹配,则将premiumtest值写入模板中的特定单元格。

import openpyxl
# getting workbook
wb = openpyxl.load_workbook(r'\server\user\Python\Template.xlsx')
# looping through worksheets
for sheet in wb.worksheets:
     sheetnames = sheet
     print(sheetnames)


for index, row in df.iterrows():
    if any(x in 'MTHLY-'+ row[0] for x in sheetnames): #[0]is the index for column StateID            
    # Then write premiumtest into cell 1

但我得到一个错误:

Traceback (most recent call last):

    if any(x in 'MTHLY-'+ row[0] for x in sheetnames):  #
  File "x:\Documents\Python\Treaty Year Report\TreatyYearReport3 - Copy.py", line 68, in <genexpr>
    if any(x in 'MTHLY-'+ row[0] for x in sheetnames):  # 
TypeError: 'in <string>' requires string as left operand, not tuple

打印(工作表名称):。

工作表名称

标签: pythonpython-3.xpandasdataframe

解决方案


获取您的代码

any(x in 'MTHLY-'+ row[0] for x in sheetnames)

正常运行,您可以获得工作表名称

sheetnames = [sheet.title for sheet in wb.worksheets]

这基本上会取代你当前的 for 循环

for sheet in wb.worksheets:
     sheetnames = sheet
     print(sheetnames)

推荐阅读