pandas :按A列对数据进行分组,按B列的现有值过滤A

编程入门 行业动态 更新时间:2024-10-24 01:54:00
本文介绍了 pandas :按A列对数据进行分组,按B列的现有值过滤A的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是熊猫的新手,想创建一个包含分组和过滤后数据的新数据集.现在,我的数据集包含两列如下所示(第一列包含A,B或C,第二列包含值):

I'm new to pandas and want to create a new dataset with grouped and filtered data. Right now, my dataset contains two columns looking like this (first column with A, B or C, second with value):

A 1 A 2 A 3 A 4 B 1 B 2 B 3 C 4

->现在,我想按第一列的键(A,B,C)进行分组,并仅显示存在值1和2的键.这样我的新数据集看起来就像:

--> now I want to group by the keys of the first column (A,B,C) , and show only the keys, where the values 1 AND 2 exist. So that my new data set looks like:

A 1 A 2 B 1 B 2

直到现在,我只能打印所有内容,但不知道如何过滤:

Until now, I'm only able to print everything but I don't know how to filter:

for name, group in data.groupby('keys'): print(name) print(group)

感谢您的帮助!

推荐答案

您可以使用:

df = df.loc[(df['col2'] == 1) | (df['col2'] == 2)]

然后过滤不包含两个值的组:

And then filter the groups that dont contains both values:

df = df.groupby('col1').filter(lambda x: any(x['col2'] == 2)) df = df.groupby('col1').filter(lambda x: any(x['col2'] == 1))

示例:

col1 col2 0 A 1 1 A 2 2 A 3 3 A 4 4 B 1 5 B 2 6 B 3 7 C 4 8 C 1

输出:

col1 col2 0 A 1 1 A 2 4 B 1 5 B 2

更多推荐

pandas :按A列对数据进行分组,按B列的现有值过滤A

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

发布评论

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

>www.elefans.com

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