Add to advanced groupby sections docs
This seem a little strange, here the integer column N is upcast when using an apply (since the row (Series) has floats in it), unfortunately in this example this means I get an exception:
from numpy.random import *
df = pd.DataFrame({'a': randn(100), 'b': randn(100), 'N': randint(10, 100, (100))})
df.dtypes
N int64
a float64
b float64
dtype: object
def f(x):
return x**2-x
def integrate_f(a, b, N):
s = 0
dx = (b-a)/N
for i in range(N):
s += f(a+i*dx)
return s * dx
df.apply(lambda x: integrate_f(x['a'], x['b'], x['N']), axis=1)---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-179-af52228271ac> in <module>()
----> 1 df.apply(lambda x: integrate_f(x['a'], x['b'], x['N']), axis=1)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.pyc in apply(self, func, axis, broadcast, raw, args, **kwds)
4116 return self._apply_raw(f, axis)
4117 else:
-> 4118 return self._apply_standard(f, axis)
4119 else:
4120 return self._apply_broadcast(f, axis)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/frame.pyc in _apply_standard(self, func, axis, ignore_failures)
4191 # no k defined yet
4192 pass
-> 4193 raise e
4194
4195
TypeError: ('range() integer end argument expected, got numpy.float64.', u'occurred at index 0')
The obvious "fix" is to use a dummy column... ahem:
df = pd.DataFrame({'x': 'x', 'a': randn(100), 'b': randn(100), 'N': randint(10, 100, (100))})
related #3926
Comment From: jreback
I don't think this is a big deal, you can easily do:
range(int(N))
inside integrate....
though at some point maybe want to have more examples / docs for apply (maybe an advanced section)?
Comment From: hayd
(re the first part: I knew you'd say that :p, still is a slight gotcha... I enjoyed my fix)
Yeah we need some column grabbing in there, is a pretty common idiom.
Comment From: jreback
yeh....I think prob need an advanced section....at some point
Comment From: MarcoGorelli
at some point
there's been no uptake on this in an entire decade, let's close