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

如何用自定义函数调用其他函数?DataFrame列分析代码报错排查

自定义DataFrame列分析类的报错与输出问题修复

问题描述

尝试编写一个类简化DataFrame列分析流程,避免重复调用.hist()、.size()、.describe()等方法,但运行时出现AttributeError: 'Rectangle' object has no property 'no_show_data'错误,且.size()等方法无输出。

原代码:

class no_show_data:
    def __init__(self, df, col_name):
        self.df = df
        self.col_name = col_name
    
    def hist(self):
        return self.df.hist(no_show_data = col_name);
    
    def describe(self):
        return self.df[col_name].describe();
    
    def size(self):
        return self.df[col_name].size();
    
    def information(self):
        print(self.hist(), self.describe(), self.size());

调用方式:

c = no_show_data(df, "age");
c.information();

错误原因与修复方案

1. .hist()方法参数错误

pandas的DataFrame.hist()通过column参数指定绘图列,而非自定义的no_show_data参数,且需用self.col_name引用实例属性。

2. 未正确引用实例属性col_name

所有方法中直接用col_name会触发变量未定义错误,必须改为self.col_name访问初始化时传入的列名。

3. .size是属性而非方法

pandas Series的size是属性,不需要加括号调用,加括号会引发错误。

4. information()方法输出逻辑问题

hist()返回Matplotlib绘图对象,直接print只会显示对象引用;应先执行绘图,再分别打印描述统计和大小信息。

修复后的代码

import matplotlib.pyplot as plt

class no_show_data:
    def __init__(self, df, col_name):
        self.df = df
        self.col_name = col_name
    
    def hist(self):
        self.df.hist(column=self.col_name)
        plt.show()
    
    def describe(self):
        return self.df[self.col_name].describe()
    
    def size(self):
        return self.df[self.col_name].size
    
    def information(self):
        self.hist()
        print("\n描述统计信息:")
        print(self.describe())
        print(f"\n列记录数:{self.size()}")

调用示例:

c = no_show_data(df, "age")
c.information()

修复说明

  • 修正hist()方法参数为column=self.col_name,添加plt.show()显示直方图
  • 所有方法统一用self.col_name访问列名
  • 去掉size()方法中size后的括号,直接返回属性值
  • 调整information()输出逻辑,分块展示直方图、描述统计和记录数,提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:15:11