python - 使用带有自定义功能的 Pandas Groupby
问题描述
我无法弄清楚我收到错误的原因。我有 pandas 0.25.1 我正在尝试使用 groupby 和自定义函数为某些数据框生成摘要。因此,假设我的 df 包含 a、c、b、d 列。我使用 groupby + 自定义函数来生成另一个数据框。每列处理不同的功能。groupby 可以单独工作,但不能一起工作。
自定义函数:
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"])
尝试这样做时:
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()
我得到:
e[('price', '<lambda>')] not in index
但这一个本身就可以正常工作:
grp = res_df.groupby('price_per_time').agg(mean_price=('price', wm)).reset_index()
我的数据框是:
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
并且预期的输出应该在一个数据框对象中包含所有应用的功能。
解决方案
推荐阅读
- android - 为什么在我的 android 项目中生成 3 个构建文件夹?
- python - 如何在列表中添加倍数?
- ruby-on-rails - 在 netlify 上托管
- reactjs - 如何将组件传递给助手?
- java - 如何使用 ThreadpoolExecutor 和 Callable Future 创建多线程代码
- python - 构造python类以确定要使用的解析器类型
- docker - 在管理器节点中创建 docker 服务
- reactjs - 创建 React App npx create-react-app react-task-tracker
- r - R将宽表格式化为长表
- java - “VerifyError:StackMapTable 错误:错误偏移”在检测类中方法的第一条指令处