2014-02-19 64 views
-1

我找不到這個問題的正確搜索條件,所以如果以前已經問過這個問題,請道歉。python函數,允許您命名列(作爲函數參數)

基本上,我想要創建一個python函數,允許您命名列(作爲函數參數),您將執行某些類型的分析。

例如見下文。很明顯,這段代碼不起作用,因爲'yearattribute'是在df之後的字面意思。我會感謝您的幫助!

def networkpairs2(df, Year): 
    """ 
    An effort to generalize the networkpairs function by allowing you to choose the 
    organization and actor parameter column names 
    """ 
    totaldf = df 
    yearattribute = '%s' %Year 
    print yearattribute 
    yearlist = list(np.unique(df.yearattribute)) 
    print yearlist 
    return 

回答

3

如果我理解你,df[yearattribute].unique()應該工作。您可以像字典一樣索引到DataFrame列中。

除了#1:totaldf = df只會使totaldf成爲df的新名稱,它不會生成副本,您也不會使用它。 #

除了#2:你沒有任何回報。

+0

D'oh。我知道我忘記了一些愚蠢的東西。我忘記了這個索引方法。 – user3314418

2

你可以在這裏使用getattr

yearlist = list(np.unique(getattr(df, yearattribute))) 

getattr使您可以通過它的名字的字符串表示訪問屬性。

下面是一個演示:

>>> class Foo: 
...  def __init__(self): 
...   self.attr = 'value' 
... 
>>> foo = Foo() 
>>> getattr(foo, 'attr') 
'value' 
>>> 
+0

非常感謝你! – user3314418