按两列分组,忽略对的顺序

编程入门 行业动态 更新时间:2024-10-28 20:21:53
本文介绍了按两列分组,忽略对的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有一个数据帧,如下所示:

Suppose we have a dataframe that looks like this:

start stop duration 0 A B 1 1 B A 2 2 C D 2 3 D C 0

什么是最好的构造以下列表的方法:i)开始/停止对; ii)开始/停止对数; iii)启动/停止对的平均持续时间?在这种情况下,顺序无关紧要:(A,B)=(B,A)。

What's the best way to construct a list of: i) start/stop pairs; ii) count of start/stop pairs; iii) avg duration of start/stop pairs? In this case, order should not matter: (A,B)=(B,A).

所需输出: [[开始,停止,计数,平均持续时间]]

在此示例中: [[A,B,2,1.5],[C,D,2,1]]

推荐答案

sort 的前两列(您可以就地执行此操作,或者创建副本并执行相同的操作;我已经完成了前者),然后 groupby 和 agg :

sort the first two columns (you can do this in-place, or create a copy and do the same thing; I've done the former), then groupby and agg:

df[['start', 'stop']] = np.sort(df[['start', 'stop']], axis=1) (df.groupby(['start','stop']) .duration .agg(['count', 'mean']) .reset_index() .values .tolist()) # [['A', 'B', 2, 1.5], ['C', 'D', 2, 1.0]]

更多推荐

按两列分组,忽略对的顺序

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

发布评论

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

>www.elefans.com

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