ling
ling

Reputation: 205

Optimize in each group Python

I tried to minimize standard deviation of column "V" for each group. So I use scipy, the code is:

This could generate a new array of "V", then I tried to apply this method for each group by using:

tt=df.groupby(by=["A","B"])
tt.minimize(equation,options={'xtol':0.001}).x

However, get an error

'DataFrameGroupBy' object has no attribute 'minimize'

Could someone gives me some advice on how to apply optimization for each group? Thanks.

Upvotes: 0

Views: 372

Answers (1)

recentadvances
recentadvances

Reputation: 177

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:

df.groupby(by=["A","B"])\
  .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

Upvotes: 1

Related Questions