当前位置: 代码网 > it编程>前端脚本>Python > Pandas groupby方法中的group_keys属性使用及说明

Pandas groupby方法中的group_keys属性使用及说明

2026年01月15日 Python 我要评论
pandas groupby方法的group_keys属性pandas版本1.5.3中groupby方法当设置group_keys=true时,会以groupby的字段为第一级索引如下述代码中time

pandas groupby方法的group_keys属性

pandas版本1.5.3中groupby方法

当设置group_keys=true时,会以groupby的字段为第一级索引

如下述代码中time_id作为第一级索引,同时保留了原dataframe(df)中的索引作为第二级索引。

>>> df.groupby(['time_id'], group_keys=true)['wap'].apply(log_return)
time_id         
0        0               nan
         1          0.000000
         2          0.000000
         3          0.000000
         4          0.000000
                      ...   
26454    5237975   -0.001228
         5237976    0.000491
         5237977   -0.005031
         5237978    0.003219
         5237979    0.003264
name: wap, length: 5237980, dtype: float64

group_keys的意思是

是否保留groupby的feature(如time_id)作为keys放入结果中,true是放,false是不放。

这也印证了帮助里的说明:

group_keys : bool, optional
when calling apply and the by argument produces a like-indexed
(i.e. :ref:a transform <groupby.transform>) result, add group keys to
index to identify pieces
. by default group keys are not included
when the result’s index (and column) labels match the inputs, and
are included otherwise. this argument has no effect if the result produced
is not like-indexed with respect to the input.

因此,当设置group_keys=false时,group keys(time_id)就不在返回结果中了,如下所示。

在设置为false是可以直接将返回结果,作为原dataframe(df)的一列,很方便。

>>> df.groupby(['time_id'], group_keys=false)['wap'].apply(log_return)
0               nan
1          0.000000
2          0.000000
3          0.000000
4          0.000000
             ...   
5237975   -0.001228
5237976    0.000491
5237977   -0.005031
5237978    0.003219
5237979    0.003264
name: wap, length: 5237980, dtype: float64

ps:对英文帮助的深入理解,需要结合实际应用。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com