python - 识别 pandas 中包含相同值但顺序不同的行

标签 python pandas

我有一个包含四列的 pandas df(Target1、Target2、Target3、All_targets)。 由于此 df 是由工具直接创建的,因此我想确定是否存在包含相同目标组合但顺序不同的行。更具体地说,我只想识别所有三个目标都相同的那些行。

这是我的数据框的可重现示例。

data = {'Target1':['IL17', 'TLR4', 'ERK', 'IL36','MEK'],
        'Target2':['CD80', 'ERK', 'IL17', 'STAT1','TLR4'],
        'Target13':['ERK', 'MEK', 'CD80', 'IL18','STAT3'],
        'All_targets':['IL17_CD80_ERK', 'TLR4_ERK_MEK', 'ERK_IL17_CD80', 'IL36_STAT1_IL18','MEK_TLR4_STAT3']}
df = pd.DataFrame(data)
df

预期的输出将是一个数据帧,其中不包含包含相同三个目标的行。

filtered_df = {'Target1':['IL17', 'TLR4', 'IL36','MEK'],
            'Target2':['CD80', 'ERK', 'STAT1','TLR4'],
            'Target13':['ERK', 'MEK', 'IL18','STAT3'],
            'All_targets':['IL17_CD80_ERK', 'TLR4_ERK_MEK', 'IL36_STAT1_IL18','MEK_TLR4_STAT3']}

提前谢谢您!

最佳答案

为按位置选择的前 3 列创建卡住集,然后按 Series.duplicated 复制,最后按 boolean indexing 过滤:

mask = df.iloc[:, :3].apply(frozenset, 1).duplicated(keep=False)
df1 = df[mask]
print (df1)

  Target1 Target2 Target13    All_targets
0    IL17    CD80      ERK  IL17_CD80_ERK
2     ERK    IL17     CD80  ERK_IL17_CD80

df2 = df[~mask]

关于python - 识别 pandas 中包含相同值但顺序不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73274573/

相关文章:

python - 无法获取与 Neo4j 数据库的连接

python - 如何更改 pandas DataFrame 标题的样式?

python - 值错误 : Supply a 'c' kwarg or a 'color' kwarg but not both; they differ but their functionalities overlap

python - 从修改值的旧列在数据框中创建新列的最简单逻辑是什么?

python - pandas groupby 并聚合到新列中

python - Pandas 根据值插入行并用 0 填充

python - 在多个 QTreeWidget 之间拖放数据

python - 如何处理/映射自定义 postgresql 类型到 Django 模型

python - 如何将weasyprint生成的PDF文件保存(存储)到指定目录?

python - 如何在不删除 Python 中的分隔符的情况下拆分具有多个分隔符的字符串?