2016-12-16 19 views
0

我正在嘗試編寫一個函數,該函數從我之前在代碼中定義的pandas DataFrame中調用特定列。我如何定義一個調用python中特定數據框列的函數/宏?

數據幀可以是簡單的東西,比如

df = pd.DataFrame(
         { 
         'col0': np.random.randint(0,100,100), 
         'col1': np.random.randint(0,100,100), 
         'col2': np.random.randint(0,100,100) 
          } 
         ) 

下一個步驟將是編寫調用COL0,COL1,COL2或功能。

def hist(x): 
    return np.histogram(
         df['x'], 
         bins = 6 
         ) 

但是,當您通過在數據幀中定義的列名調用函數,Python不認識的名字;

In [1]: hist(col1) 
Traceback (most recent call last): 

    File "<ipython-input-68-e860df6abc8e>", line 1, in <module> 
    hist(col1) 

NameError: name 'col1' is not defined 

是否有解決此問題的方法?

+0

您已經GIOT混了變量名的字符串。 'df ['x']'必須是'df [x]',並且函數調用中的'col1'必須是'「col1」'。 – DyZ

回答

0

你在混合字符串和變量。你可能想是這樣

def hist(x): 
    return np.histogram(
         df[x], # no quotes! You want the value of x here, not a literal "x" 
         bins = 6 
         ) 

,並調用它像這樣:

foo = hist('col1') # quotes necessary since you're passing the string "col1" 

否則,Python將一個名爲col1變量,尚未確定。

0

您應該刪除X的引號,把一個字符串作爲函數的輸入與列的名稱:

def hist(x): 
    return np.histogram(df[x], bins = 6) 

hist('col1') 
相關問題