2017-08-31 35 views
-2

當我嘗試執行函數時,收到NameError(名稱'loan tape'未定義)。 函數定義的方式有什麼問題?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

如果這是所有的代碼,那麼該錯誤是正確的。沒有定義變量'loan_tape'。 –

+2

您是否試圖讓名稱爲「loan_tape」的數據框初始化? –

+0

他在函數參數中使用的loan_type變量的定義在哪裏? –

回答

1

如果你在做什麼,我認爲 - 這是試圖預先創建一個變量並初始化它作爲一個數據幀,那麼這絕對是你不能怎麼做。

傳遞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 

請注意,您不能返回print(...)因爲print回報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"]]) 
+0

準確!非常感謝!還有一個問題。我如何讓列名可以在函數參數中輸入? –

+0

@PabloRodriguez編輯。希望能幫助到你。 –