如何在Pandas中不依赖额外包实现缺失值模式可视化
Pandas+Matplotlib实现缺失值模式可视化
实现思路
核心逻辑是将DataFrame转换为布尔型缺失值矩阵,用灰度图渲染矩阵:非缺失值映射为深色,缺失值映射为白色,完全匹配需求的显示效果,无需引入任何第三方依赖。
基础版实现(仅缺失值矩阵)
import pandas as pd import matplotlib.pyplot as plt # 替换为你自己的数据集即可 df = pd.DataFrame({ 'col1': [1, 2, None, 4, None, 6, 7, None], 'col2': [None, 2, 3, None, 5, None, 7, 8], 'col3': [1, None, 3, 4, 5, None, None, 8], 'col4': [1, 2, 3, 4, 5, 6, 7, 8], 'col5': [None, None, None, 4, 5, 6, 7, None] }) # 转换为缺失值布尔矩阵:True对应缺失值,False对应非缺失值 null_matrix = df.isnull() plt.figure(figsize=(12, 6)) # cmap='gray'对应灰度渲染:值为1(True/缺失)显示为白色,值为0(False/非缺失)显示为黑色 # interpolation='none'关闭插值,单元格边界清晰无模糊 plt.imshow(null_matrix, cmap='gray', aspect='auto', interpolation='none') # 设置x轴刻度为列名,旋转45度避免重叠 plt.xticks(ticks=range(len(df.columns)), labels=df.columns, rotation=45, ha='right') plt.yticks(ticks=range(len(df)), labels=df.index) plt.xlabel('数据列') plt.ylabel('样本索引') plt.tight_layout() plt.show()
进阶版实现(带列缺失数量统计,和参考效果完全对齐)
在矩阵上方添加每列缺失数量的统计条,还原专业缺失值可视化工具的完整效果:
import pandas as pd import matplotlib.pyplot as plt # 替换为自己的数据集 df = pd.DataFrame({ 'col1': [1, 2, None, 4, None, 6, 7, None], 'col2': [None, 2, 3, None, 5, None, 7, 8], 'col3': [1, None, 3, 4, 5, None, None, 8], 'col4': [1, 2, 3, 4, 5, 6, 7, 8], 'col5': [None, None, None, 4, 5, 6, 7, None] }) null_matrix = df.isnull() # 统计每列缺失数量 null_count = null_matrix.sum() # 划分布局:顶部1份高度放统计柱状图,底部5份高度放缺失值矩阵 fig, (ax_bar, ax_matrix) = plt.subplots( nrows=2, ncols=1, figsize=(12, 7), gridspec_kw={'height_ratios': [1, 5]} ) # 绘制顶部缺失数量柱状图 ax_bar.bar(x=range(len(null_count)), height=null_count, color='gray') ax_bar.set_xticks([]) # 隐藏柱状图x轴刻度,和下方矩阵共用刻度 ax_bar.set_ylabel('缺失数量') # 绘制底部缺失值矩阵 ax_matrix.imshow(null_matrix, cmap='gray', aspect='auto', interpolation='none') ax_matrix.set_xticks(ticks=range(len(df.columns)), labels=df.columns, rotation=45, ha='right') ax_matrix.set_yticks(ticks=range(len(df)), labels=df.index) ax_matrix.set_xlabel('数据列') ax_matrix.set_ylabel('样本索引') plt.tight_layout() plt.show()
如果需要调整非缺失值的显示颜色,仅需修改cmap参数即可,比如cmap='Blues'会将非缺失值显示为蓝色,缺失值依然为白色。
内容的提问来源于stack exchange,提问作者Mykola Zotko
相关产品推荐
相关产品推荐

