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

如何绘制分类变量交叉计数统计图?代码报错求助

解决Seaborn catplot报错及交叉分类计数统计问题

看起来你在尝试用Seaborn绘制交叉分类计数图时遇到了报错,同时还需要统计特定分类组合的患者数量,我来帮你一步步搞定:

一、先解决catplot的TypeError错误

你抛出的TypeError: object of type 'NoneType' has no len()是因为没有给catplot传入data参数。Seaborn的catplot要求你先通过data参数传入完整的DataFrame,然后y、hue这类参数只需要传入对应的列名字符串就行,而不是直接传Series对象。

修正后的代码如下:

import seaborn as sns

sns.catplot(
    y='max_glu_serum', 
    hue='readmitted', 
    data=train_data_wmis,  # 必须传入完整的数据集DataFrame
    kind="count", 
    palette="pastel", 
    edgecolor=".6", 
    dropna=True
)

这样就能正常生成你需要的分类计数图啦。

二、统计特定组合的患者数量

如果你只是想得到max_glu_serum=<300且readmitted=>30的患者数,其实不用画图,直接用Pandas就能快速计算,这里给你两种方法:

  • 方法1:布尔索引直接筛选
    用布尔条件精准定位目标数据,然后统计长度:

    target_patients = train_data_wmis[(train_data_wmis['max_glu_serum'] == '<300') & (train_data_wmis['readmitted'] == '>30')]
    count = len(target_patients)
    print(f"符合条件的患者数量:{count}")
    
  • 方法2:交叉表查看所有组合(更直观)
    用pd.crosstab生成两列分类变量的交叉计数表,既能看到目标值,也能查看其他组合的情况:

    import pandas as pd
    
    # 生成交叉计数表,自动排除缺失值
    cross_table = pd.crosstab(
        train_data_wmis['max_glu_serum'], 
        train_data_wmis['readmitted'],
        dropna=True
    )
    print("所有分类组合的计数表:")
    print(cross_table)
    
    # 提取目标组合的数量
    target_count = cross_table.loc['<300', '>30']
    print(f"\nmax_glu_serum=<300且readmitted=>30的患者数量:{target_count}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:47:33