我有这段代码:
ces2gTable = pd.DataFrame()
ces4gTable = pd.DataFrame()
..
else:
#print("Это выгрузка из сайта CES")
cols = [2, 6, 7, 8, 10, 14]
table = pd.read_excel(locDir+"/"+file, usecols=cols)
table = table[table["BSS"].isna()]
#print(table)
with open("output.log", "a") as outfile:
outfile.write("+ File contents received "+file+"\n")
if "BS_address" in table:
ces2gTable = pd.concat([ces2gTable,table])
elif "RMOD" in table:
ces4gTable = pd.concat([ces4gTable,table])
else:
with open("output.log", "a") as outfile:
outfile.write("- Некорректная таблица в файле "+file+"\n")
with open("output.log", "a") as outfile:
outfile.write("+ The necessary 2g 4g data from the file has been loaded into the tables "+file+"\n")
#print(table)
print("Таблицы (ces2gTable, ces4gTable) из сайта CES для того, чтобы посмотреть какие данные на сайте не заполнены:")
print(ces2gTable)
print(ces4gTable)
如何将这样的代码转换为函数?我到处重复这个代码。仅列的读数发生变化。我尝试这样做:
ces2gTable = pd.DataFrame()
ces4gTable = pd.DataFrame()
def cesTable(col1, col2, col3, col4, col5, col6):
cols = [col1, col2, col3, col4, col5, col6]
table = pd.read_excel(locDir+"/"+file, usecols=cols)
table = table[table["BSS"].isna()]
#print(table)
with open("output.log", "a") as outfile:
outfile.write("+ File contents received "+file+"\n")
if "BS_address" in table:
ces2gTable = pd.concat([ces2gTable,table])
elif "RMOD" in table:
ces4gTable = pd.concat([ces4gTable,table])
else:
with open("output.log", "a") as outfile:
outfile.write("- Некорректная таблица в файле "+file+"\n")
with open("output.log", "a") as outfile:
outfile.write("+ The necessary 2g 4g data from the file has been loaded into the tables "+file+"\n")
#print(table)
return table
...
else:
#print("Это выгрузка из сайта CES")
cesTable(2, 6, 7, 8, 10, 14)
print("Таблицы (ces2gTable, ces4gTable) из сайта CES для того, чтобы посмотреть какие данные на сайте не заполнены:")
print(ces2gTable)
print(ces4gTable)
但我收到一个错误:
Traceback (most recent call last):
File "P:\projects\FillingInDataForTheSite\py.py", line 150, in <module>
cesTable(2, 6, 7, 8, 10, 14)
File "P:\projects\FillingInDataForTheSite\py.py", line 17, in cesTable
ces4gTable = pd.concat([ces4gTable,table])
UnboundLocalError: local variable 'ces4gTable' referenced before assignment
出现此错误的原因是函数中使用了局部变量。默认情况下,你可以获取全局变量的值,但不能更改它们。因此,不是更改现有变量
ces4gTable,而是在函数内创建一个新变量。当创建一个新的局部变量时,它就会被访问。这会导致错误。也会有类似的问题ces2gTable。在函数定义之后添加以下行:
值得注意的是,使用全局变量被认为是不好的做法,不建议使用,因此请自行决定是否值得使用。