我有一个这样的数据框

df = pd.DataFrame({'patient': ['patient1', 'patient1', 'patient1','patient2', 'patient2', 'patient3','patient3','patient4'], 
                   'gene':['TYR','TYR','TYR','TYR','TYR','TYR','TYR','TYR'],
                   'variant': ['buu', 'luu', 'stm','lol', 'bla', 'buu', 'lol','buu'],
                    'genotype': ['hom', 'het', 'hom','het', 'hom', 'het', 'het','het']})
df

 patient    gene    variant genotype
0   patient1    TYR buu hom
1   patient1    TYR luu het
2   patient1    TYR stm hom
3   patient2    TYR lol het
4   patient2    TYR bla hom
5   patient3    TYR buu het
6   patient3    TYR lol het
7   patient4    TYR buu het

我想确定哪些患者有BUU和其他变种,但没有LUU.因此,预期的输出应该是这样的

patient gene variant genotype

patient3  TYR     buu      het
patient3  TYR     lol      het

我怎么能这样做呢?

推荐答案

您也可以try 以下解决方案:

import pandas as pd

# First we filter out those groups that have only 1 observations
g = df.groupby('patient').filter(lambda x: len(x) > 1)

# Then we apply both of our desired conditions
m = (g.groupby('patient')['variant'].transform(lambda x: x.eq('buu').any() & (~ x.eq('luu').any())))

g.loc[m]

    patient gene variant genotype
5  patient3  TYR     buu      het
6  patient3  TYR     lol      het

Python相关问答推荐

数字梯度的意外值

通过交换 node 对链接列表进行 Select 排序

将轨迹优化问题描述为NLP.如何用Gekko解决这个问题?当前面临异常:@错误:最大方程长度错误

如何让 turtle 通过点击和拖动来绘制?

即使在可见的情况下也不相互作用

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

如何使用symy打印方程?

将整组数组拆分为最小值与最大值之和的子数组

通过pandas向每个非空单元格添加子字符串

Python中绕y轴曲线的旋转

需要帮助重新调整python fill_between与数据点

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?

搜索按钮不工作,Python tkinter

用SymPy在Python中求解指数函数

在Google Drive中获取特定文件夹内的FolderID和文件夹名称

从一个df列提取单词,分配给另一个列

如何在Python中将超链接添加到PDF中每个页面的顶部?

当输入是字典时,`pandas. concat`如何工作?

如何使用大量常量优化代码?

来自Airflow Connection的额外参数