2014-02-19 65 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