UnboundLocalError: local variable 'data' referenced before assignment

未关闭
#1,131 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
20/100
Issue 类型
缺陷
描述清晰度
需要澄清
活跃度
停滞
技术栈
pandas, python
领域
tooling

调研方向

从 issue 中的代码开始,尤其是 outer_function 和读取 Sheet1 的循环。运行示例以复现 UnboundLocalError,然后跟踪数据被赋值和使用的路径;完成的标准是示例能够处理相关的工作表内容,而不会引用未设置的局部变量。

由索引模型根据 Issue 内容生成。

描述

import xlsxwriter
import pandas as pd
import openpyxl
import pandas as pd

current=1
i = 0
counter=0

Create some Pandas dataframes from some data.

df1 = pd.DataFrame({'Data1': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data2': [21, 22, 23, 24,25]})
df3 = pd.DataFrame({'Data3': [31, 32, 33, 34,35,36]})
df4 = pd.DataFrame({'Data4': [41, 42, 43, 44,45,46,47]})
df5 = pd.DataFrame({'Data5': [51, 52, 53, 54,55,56,57,58]})

Create a Pandas Excel writer using XlsxWriter as the engine.

writer = pd.ExcelWriter('pandas_positioning.xlsx', engine='xlsxwriter')

Position the dataframes in the worksheet.

df1.to_excel(writer, sheet_name='Sheet1',startrow=0) # Default position, cell A1.
df2.to_excel(writer, sheet_name='Sheet1', startcol=0,startrow=5)
df3.to_excel(writer, sheet_name='Sheet1', startrow=0,startcol=11)
df3.to_excel(writer, sheet_name='Sheet1', startrow=0,startcol=18)
df3.to_excel(writer, sheet_name='Sheet1', startrow=0,startcol=26)

It is also possible to write the dataframe without the header and index.

#df4.to_excel(writer, sheet_name='Sheet1', startrow=7, startcol=4, header=False, index=False)

Close the Pandas Excel writer and output the Excel file.

writer.save()

def outer_function():
import xlrd
wb=xlrd.open_workbook('C:/Users/bened/pandas_positioning.xlsx')
sheet=wb.sheet_by_name('Sheet1')

for i in range(sheet.nrows):
    if(sheet.cell_value(i,0)=='Data3'):
            data=i
    d=0
    while(d<data):
        print('hi')
        break

outer_function()

how do i solve UnboundLocalError: local variable 'data' referenced before assignment
主要语言
Python
星标
35.4k
派生
12.9k
平均合并
2 小时 37 分钟
30 天内合并 PR
1

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

geekcomputers/Python 的其他 Issue

查看 geekcomputers/Python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。