You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中动态获取韦恩图各区域的元素组合

动态获取韦恩图各区域元素的通用方案

以下是一个无需手动编写集合运算的通用函数,支持通过iloc/loc任意选择DataFrame的2-6列,自动生成韦恩图各区域的元素集合及对应标签:

通用实现函数

import pandas as pd

def get_venn_regions(selected_df):
    # 将选中列转换为{列名: 非空元素集合}的字典
    set_dict = {col: set(selected_df[col].dropna()) for col in selected_df.columns}
    keys = list(set_dict.keys())
    region_map = {}
    
    # 遍历所有非空子集(对应韦恩图的每个独立区域)
    for mask in range(1, 1 << len(keys)):
        # 筛选当前区域对应的列名集合
        include_cols = [keys[i] for i in range(len(keys)) if (mask >> i) & 1]
        exclude_cols = [key for key in keys if key not in include_cols]
        
        # 计算当前区域的元素:属于所有包含列的交集,且不属于任何排除列
        region_elements = set_dict[include_cols[0]].copy()
        for col in include_cols[1:]:
            region_elements.intersection_update(set_dict[col])
        for col in exclude_cols:
            region_elements.difference_update(set_dict[col])
        
        # 生成区域标签
        if len(include_cols) == 1:
            label = f"{include_cols[0]} only"
        else:
            label = " & ".join(include_cols)
        
        # 仅保留含元素的区域
        if region_elements:
            region_map[label] = region_elements
    
    return region_map

测试示例

以你提供的音乐家数据集为例,验证函数效果:

# 构造数据集
musiciansdf = pd.DataFrame({
    "Members of The Beatles": ["Paul McCartney", "John Lennon", "George Harrison", "Ringo Starr"],
    "Members of The Beats": ["Paul McCartney", "Lennon", "George Harrison", "Starr"],
    "Guitarists": ["John Lennon", "George Harrison", "Jimi Hendrix", "Eric Clapton"],
    "Played at Woodstock": ["Jimi Hendrix", "Carlos Santana", "Keith Moon", "Carlos Santana"],
    "Played at more": ["Jimi Hendrix", "Santana", "Keith Moon", "Santana"],
    "Cheese factory": ["Jimi", "Carlos Santana", "Keith", "Carlos Santana"]
})

# 用iloc选择前2列
selected_data = musiciansdf.iloc[:, 0:2]
# 获取韦恩图区域元素
venn_regions = get_venn_regions(selected_data)

# 打印结果
import pprint
pprint.pprint(venn_regions)

输出结果

{'Members of The Beatles & Members of The Beats': {'George Harrison',
                                                  'Paul McCartney'},
 'Members of The Beatles only': {'John Lennon', 'Ringo Starr'},
 'Members of The Beats only': {'Lennon', 'Starr'}}

结合绘图使用

无论你选择pyvenn还是matplotlib-venn,都可以在绘图的同时调用该函数获取区域元素:

搭配pyvenn

from venn import venn

# 转换为集合字典用于绘图
set_dict = {col: set(selected_data[col].dropna()) for col in selected_data.columns}
# 绘制韦恩图
venn(set_dict)
# 获取区域元素(已在之前步骤完成)
# venn_regions = get_venn_regions(selected_data)

搭配matplotlib-venn(以2列为例)

from matplotlib_venn import venn2
import matplotlib.pyplot as plt

set_a = set_dict["Members of The Beatles"]
set_b = set_dict["Members of The Beats"]
# 绘制韦恩图
venn2([set_a, set_b], ("Members of The Beatles", "Members of The Beats"))
plt.show()
# 获取区域元素
# venn_regions = get_venn_regions(selected_data)

功能特点

  • 支持任意数量的列(2-6列最适合韦恩图展示)
  • 兼容iloc/loc的任意列选择方式,不限制列顺序
  • 自动过滤无元素的空区域
  • 标签格式直观:单集合区域标注“only”,多集合交集用“&”连接

内容的提问来源于stack exchange,提问作者anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 15:26:08