我找不到这个问题的正确搜索字词,所以如果之前已经提出这个问题,请道歉。
基本上,我想创建一个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
答案 0 :(得分:3)
如果我了解你,df[yearattribute].unique()
应该有效。您可以像字典一样索引DataFrame列。
除了#1:totaldf = df
只为totaldf
添加df
新名称,它不会复制,也不会使用它。
除了#2:你没有回来任何东西。
答案 1 :(得分:2)
您可以在此处使用getattr
:
yearlist = list(np.unique(getattr(df, yearattribute)))
getattr
允许您通过其名称的字符串表示来访问属性。
以下是演示:
>>> class Foo:
... def __init__(self):
... self.attr = 'value'
...
>>> foo = Foo()
>>> getattr(foo, 'attr')
'value'
>>>