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

Python类中如何将第一个方法的输出作为第二个方法的输入

解决extraction类中null_checking方法结果传递给variance方法的问题

问题根源

  • null_checking方法中的x是局部变量,未存储为类的实例属性,导致variance方法无法访问该数据
  • null_checking内的循环逻辑完全无效:enumerate(datasets1)遍历的是DataFrame的列索引与列名,items为整数类型,和字符串'True'的判断毫无意义
  • variance方法中调用x.inner_display()属于错误用法,DataFrame无此方法,且x未定义

修复后的完整代码

# 导入依赖
from statsmodels.stats.outliers_influence import variance_inflation_factor
import pandas as pd

# 导入数据集
datasets = pd.read_csv('Car_sales.csv')
features = ['Fuel_efficiency', 'Power_perf_factor', 'Engine_size', 'Horsepower', 'Fuel_capacity', 'Curb_weight']

class extraction():
    def __init__(self, datasets, features):
        self.features = features
        self.datasets = datasets
        self.cleaned_data = None  # 初始化实例属性,用于存储去空后的数据集

    def null_checking(self):
        # 提取指定特征列
        datasets1 = self.datasets[self.features]
        # 直接删除含空值的行,无需多余循环
        self.cleaned_data = datasets1.dropna(axis=0)
        print("去空后的数据集:")
        print(self.cleaned_data)

    def variance(self):
        # 先检查是否已生成去空数据
        if self.cleaned_data is None:
            print("请先调用null_checking方法生成去空后的数据集!")
            return
        
        # 复制数据避免修改原实例属性
        x = self.cleaned_data.copy()
        # 添加VIF计算所需的截距项
        x['intercept'] = 1
        print("添加截距后的数据集:")
        print(x)
        
        # 计算VIF并生成结果表
        df = pd.DataFrame()
        df['variables'] = x.columns
        df['VIF'] = [variance_inflation_factor(x.values, i) for i in range(x.shape[1])]
        print("VIF计算结果:")
        print(df)

# 使用示例
extractor = extraction(datasets, features)
extractor.null_checking()
extractor.variance()

关键修改说明

  • 在__init__中新增self.cleaned_data实例属性,专门存储去空后的数据集,实现同一类内方法间的数据共享
  • 删除null_checking中无意义的循环逻辑,简化去空操作
  • 在variance方法中增加前置检查,避免未执行null_checking就调用variance导致报错
  • 修复VIF计算参数:使用x.values传入函数,避免索引相关问题
  • 移除未使用的依赖导入,精简代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:39:35