0

I can't figure out the reason for an error I get. I have pandas 0.25.1 I'm trying to generate a summary for certain Data Frame, using groupby and custom functions. So let's say my df contains a,c,b,d columns. I use groupby + custom functions to generate another dataframe. Each column is handled with different function. The groupby works fine separately but not for all of them together.

Custom Functions:

wm = lambda x: np.average(x, weights=res_df.loc[x.index, "trips"])
ws = lambda x: np.dot(x, res_df.loc[x.index, "trips"])

When trying to do:

grp = res_df.groupby('price_per_time').agg(tot_trips=('trips', 'sum'),
tot_price=('price', 'sum'), 
sw=('sw', 'sum'), 
mean_travel_time=('travel_time', wm),
mean_price=('price', wm)).reset_index()

I get: e[('price', '<lambda>')] not in index

but this one works fine by itself:

grp = res_df.groupby('price_per_time').agg(mean_price=('price', wm)).reset_index()

My dataframe is:

    o   d   trips   travel_time     price   tam_trips   tam_times   scheme  price_per_time  length  trips_0     u   sw
0   1   2   0.999252    6.473970    0.033425    1.0     6.484416    delta   0.3     12.768381   2.17599     -0.163520   1.339307
1   1   3   0.899768    6.273440    0.012032    0.9     6.277106    delta   0.3     10.608779   1.95292     -0.157438   1.206515
2   1   4   0.199503    8.527206    0.124777    0.2     8.596922    delta   0.3     14.641428   0.44795     -0.219419   0.265286
3   1   5   0.099235    12.971093   0.331213    0.1     13.106045   delta   0.3     24.021962   0.23877     -0.340838   0.129906

And the expected output should have all the applied function in one dataframe object.

ron zuk
  • 9
  • 2
  • Can you please include a _small_ subset of your data as a copyable piece of code that can be used for testing as well as your expected output for the provided data. It's really helpful to have something to test against. – Henry Ecker May 29 '21 at 17:32
  • Sure, how can i share here dataframe? – ron zuk May 29 '21 at 17:52
  • If you need assistance formatting a small sample of your DataFrame as a copyable piece of code for SO see [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15497888). – Henry Ecker May 29 '21 at 17:55
  • The code works fine for me in version pandas 1.2.4. What version are you using? – Henry Ecker May 29 '21 at 18:04
  • @Henry Ecker 0.21.1 – ron zuk May 29 '21 at 18:14

0 Answers0