修复分配前引用的错误变量,并简化
我有一个Python项目,我尝试将其连接到SQL数据库,并具有根据返回的结果来设置数据框的功能。
他们的问题是,一旦我运行代码崩溃并显示以下错误:
名称:分配前引用的免费变量“颜色” 封闭范围
代码:
import pyodbc
import pandas as pd
import numpy as np
import streamlit as st
@st.experimental_singleton
def connect_db():
con = pyodbc.connect(
driver="ODBC Driver 17 for SQL Server",
Server = "192.168.21.132",
DATABASE="tasks",
UID="xxxx",
PWD="xxxx",
)
cursor = con.cursor()
return con
def highlight_rows(row):
value = row.loc["status_type"]
if value == "done":
color = "#ffffff"
elif value == "pending":
color = "#474d51"
return [f'background-color: {color}' for _ in row]
con = connect_db()
df = pd.read_sql_query('select * from tasks.dbo.info',con)
st.dataframe(df.reset_index(drop=True).style.apply(highlight_rows,axis = 1),height = 500)
i have a python project where i try to connect to SQL database and having function that style the dataframe based on the returned results.
Them problem is that once i run the code it crash and display the below error:
NameError: free variable 'color' referenced before assignment in
enclosing scope
code:
import pyodbc
import pandas as pd
import numpy as np
import streamlit as st
@st.experimental_singleton
def connect_db():
con = pyodbc.connect(
driver="ODBC Driver 17 for SQL Server",
Server = "192.168.21.132",
DATABASE="tasks",
UID="xxxx",
PWD="xxxx",
)
cursor = con.cursor()
return con
def highlight_rows(row):
value = row.loc["status_type"]
if value == "done":
color = "#ffffff"
elif value == "pending":
color = "#474d51"
return [f'background-color: {color}' for _ in row]
con = connect_db()
df = pd.read_sql_query('select * from tasks.dbo.info',con)
st.dataframe(df.reset_index(drop=True).style.apply(highlight_rows,axis = 1),height = 500)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生错误是因为您没有指定
value
的值可能是“ done”
或“ perdending”
之外的任何其他条件。可以通过在函数
righlight_rows
中使用else
子句:The error occurs because you did not specify a condition where the value of
value
could be anything other than"done"
or"pending"
.It can be avoided by having an
else
clause inside your functionhighlight_rows
: