optimize a group python code for each

Use the apply method to run arbitrary Python functions on each group. minimize is a function in SciPy (not Pandas) and in your case, the solution will look something like this:

  .apply(lambda g: minimize(equation, g.V, options={'xtol':0.001}).x)

Full working example:

>>> import pandas as pd
>>> from scipy.optimize import minimize, rosen
>>> df = pd.DataFrame({'A': list("abab"), 'B': list("cdcd"), 'V': [1, 2, 3, 4]})
>>> df.groupby(by=["A","B"]).apply(lambda g: minimize(rosen, g.V, options={'xtol':0.001}).x)
A  B
a  c    [0.9999955536845236, 0.9999911035369479]
b  d    [0.9999980290689747, 0.9999959871180912]
dtype: object

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top