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

如何实现Pandas每次迭代绘制5列无重复的散点图?

问题分析与解决方案

原代码的问题在于用zip(df.columns[n:], df.columns[n+1:], df.columns[n+2:], df.columns[n+3:], df.columns[n+4:])的方式会让每次迭代的列是连续错位重叠的——比如第一次取第n到n+4列,第二次取n+1到n+5列,自然会重复绘制大部分列。

要实现「每次迭代绘制5列且无重复」,核心是把从n开始的列按每5个为一组做无重叠划分,再逐组绘制。

修改后的代码

import matplotlib.pyplot as plt
import seaborn as sns

n = 4
target_cols = df.columns[n:]  # 获取从第n列开始的所有目标列

# 按步长5遍历目标列,每次取5个不重叠的列
for i in range(0, len(target_cols), 5):
    current_group = target_cols[i:i+5]
    # 根据当前组的列数创建子图(处理最后一组不足5列的情况)
    fig, axs = plt.subplots(ncols=len(current_group), tight_layout=True, sharey=True, figsize=(4*len(current_group), 3))
    # 遍历当前组的列和对应的子图
    for col, ax in zip(current_group, axs):
        sns.scatterplot(df, x=col, y='variable', ax=ax)
    plt.show()

关键改动说明

  • 先提取所有需要绘制的目标列target_cols = df.columns[n:],避免重复操作
  • 用range(0, len(target_cols), 5)生成每组的起始索引,步长设为5,保证每组列无重叠
  • 处理最后一组可能不足5列的情况:子图数量匹配当前组的列数,避免报错
  • 用循环遍历当前组的列和子图,替代原代码中重复的5行绘图代码,更简洁易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:15:32