python - Using partial with groupby and apply in Pandas -
i having trouble using partial groupby , apply in pandas. perhaps not using right?
data = {'a':[1,1,2,2],'b':['y','y','n','y'], 'c':['y','y','n','y']} df = pandas.dataframe(data) def county(columnname, group): return len(group[group[columnname] == 'y']) df.groupby('a').apply(partial(county, 'b'))
attributeerror: 'functools.partial' object has no attribute '_module_'
welcome@welcome-thinkcentre-edge72:~$ python python 2.7.3 (default, feb 27 2014, 19:58:35) [gcc 4.6.3] on linux2 type "help", "copyright", "credits" or "license" more information. >>> import pandas >>> functools import partial >>> data = {'a':[1,1,2,2],'b':['y','y','n','y'], 'c':['y','y','n','y']} >>> df = pandas.dataframe(data) >>> def county(columnname, group): return len(group[group[columnname] == 'y']) ... >>> df.groupby('a').apply(partial(county, 'b')) traceback (most recent call last): file "<stdin>", line 1, in <module> file "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 420, in apply @wraps(func) file "/usr/lib/python2.7/functools.py", line 33, in update_wrapper setattr(wrapper, attr, getattr(wrapped, attr)) attributeerror: 'functools.partial' object has no attribute '__module__' >>> pandas.__version__ '0.13.1' >>>
there no need use functools.partial
here, can provide arguments function inside apply
call.
if function has first argument group (so switch order of arguments), other arguments in apply
passed function , in way can specify columnname
in apply:
in [10]: def county2(group, columnname): ...: return len(group[group[columnname] == 'y']) ...: in [11]: df.groupby('a').apply(county2, 'b') out[11]: 1 2 2 1 dtype: int64
the reason not work partial, functools.wraps
not seem work functools.partial
(wraps
used inside apply).
Comments
Post a Comment