Pandas Groupby First

编程入门 行业动态 更新时间:2024-10-27 13:23:26
本文介绍了Pandas Groupby First - 从原始数据帧中提取索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个非常简单的问题.我想获取一个数据框,对某些列执行 groupby,并提取每个组中第一行的索引(在原始数据框中).我该怎么做?

I have a very simple problem. I'd like to take a data frame, perform a groupby on some columns, and extract the index (in the original data frame) of the first row in each group. How do I do this?

我尝试过使用 as_index、group_keys、reset_index(),但似乎没有任何效果.

I've tried playing with as_index, group_keys, reset_index() and nothing seems to work.

推荐答案

你需要first函数:

x = pd.DataFrame([{'name': 'b1', 'group': 'a'}, {'name': 'b2', 'group': 'a'}, {'name': 'b3', 'group': 'a'}, {'name': 'b4', 'group': 'b'}, {'name': 'b5', 'group': 'b'}, {'name': 'b6', 'group': 'a'}, {'name': 'b7', 'group': 'c'}, {'name': 'b8', 'group': 'c'},]) x = x.reset_index() # add the indices as a column xc = x.groupby('group').first() print(xc) index name group a 0 b1 b 3 b4 c 6 b7

更多推荐

Pandas Groupby First

本文发布于:2023-10-31 08:02:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Pandas   Groupby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!