NameError: name 'loan_tape' is not defined when trying to call a function
NameError: name 'loan_tape' is not defined when trying to call a function
我在尝试执行函数时收到 NameError(名称 'loan tape' 未定义)。
函数的定义方式有什么问题?
def create_table(table_name, num_rows, num_cols):
table_name = pd.DataFrame(np.random.rand(num_rows,num_cols), columns = [["Exposure","EIR"]])
return print(table_name.head(20))
(create_table(loan_tape ,20 ,2)
如果您正在按照我的想法行事 - 即尝试提前创建一个变量并将其初始化为数据框,那么这绝对不是您的做法。
传递 2 个参数,因为这就是您所需要的,然后 return table
。
def create_table(num_rows, num_cols):
table = pd.DataFrame(np.random.rand(num_rows,num_cols),
columns=[["Exposure","EIR"]]
)
return table.head(20)
loan_tape = create_table(20, 2)
print(loan_tape)
Exposure EIR
0 0.969132 0.379487
1 0.695092 0.787540
2 0.168266 0.989034
3 0.867826 0.499139
4 0.447891 0.922618
5 0.970134 0.252184
6 0.971446 0.049291
7 0.289744 0.797935
8 0.460266 0.176311
9 0.927201 0.280241
10 0.671764 0.520443
11 0.196516 0.258724
12 0.391544 0.190949
13 0.742233 0.590536
14 0.092953 0.558999
15 0.573201 0.505211
16 0.933630 0.656285
17 0.327771 0.264572
18 0.279868 0.527335
19 0.096123 0.560708
请注意,您不能 return print(...)
因为 print
returns None
.
编辑:将 columns
作为参数传递:
def create_table(num_rows, num_cols, use_cols):
table = pd.DataFrame(np.random.rand(num_rows,num_cols),
columns=use_cols)
return table.head(20)
loan_tape = create_table(20, 2, [["Exposure","EIR"]] )
我在尝试执行函数时收到 NameError(名称 'loan tape' 未定义)。 函数的定义方式有什么问题?
def create_table(table_name, num_rows, num_cols):
table_name = pd.DataFrame(np.random.rand(num_rows,num_cols), columns = [["Exposure","EIR"]])
return print(table_name.head(20))
(create_table(loan_tape ,20 ,2)
如果您正在按照我的想法行事 - 即尝试提前创建一个变量并将其初始化为数据框,那么这绝对不是您的做法。
传递 2 个参数,因为这就是您所需要的,然后 return table
。
def create_table(num_rows, num_cols):
table = pd.DataFrame(np.random.rand(num_rows,num_cols),
columns=[["Exposure","EIR"]]
)
return table.head(20)
loan_tape = create_table(20, 2)
print(loan_tape)
Exposure EIR
0 0.969132 0.379487
1 0.695092 0.787540
2 0.168266 0.989034
3 0.867826 0.499139
4 0.447891 0.922618
5 0.970134 0.252184
6 0.971446 0.049291
7 0.289744 0.797935
8 0.460266 0.176311
9 0.927201 0.280241
10 0.671764 0.520443
11 0.196516 0.258724
12 0.391544 0.190949
13 0.742233 0.590536
14 0.092953 0.558999
15 0.573201 0.505211
16 0.933630 0.656285
17 0.327771 0.264572
18 0.279868 0.527335
19 0.096123 0.560708
请注意,您不能 return print(...)
因为 print
returns None
.
编辑:将 columns
作为参数传递:
def create_table(num_rows, num_cols, use_cols):
table = pd.DataFrame(np.random.rand(num_rows,num_cols),
columns=use_cols)
return table.head(20)
loan_tape = create_table(20, 2, [["Exposure","EIR"]] )