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

Python:如何将R2达标列复制至新表?修复AttributeError问题

问题解决:将高R²值的列迁移至新表

你遇到的AttributeError: 'DataFrame' object has no attribute 'column'是因为代码里的X.column写法错误——X是DataFrame对象,并没有名为column的属性,你要引用的是循环中当前迭代的列名变量column。

另外你的代码还有两处逻辑问题:

  • 每次循环都重新读取best_fit.csv,会覆盖之前添加的列数据,应该把读取操作放在循环外面
  • 直接用df_2 = df[column].copy()会把df_2替换成单列Series,而不是在已有的空表中填充对应列的数据

以下是修正后的完整代码:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt

# 假设你已经定义了X、y、df这些变量
# 提前读取空表,避免循环内重复读取重置数据
df_2 = pd.read_csv('best_fit.csv')

for column, value in X.items():
    value = value.values.reshape(-1, 1)
    X_train, X_test, y_train, y_test = train_test_split(value, y, test_size=0.25, random_state=50)

    regression = LinearRegression()
    regression.fit(X_train, y_train)
    cutoff = 0.999    

    def line_eq(m, x, c):
        return m * x + c

    def line_val(val):
        v = val[:]
        line_val = np.sqrt(np.sum(((y - line_eq(value, *v))**2)))
        return line_val
  
    line = optimize.minimize(line_val, [1, -1])
    y_fit = line_eq(value, *line.x[:2])
    plt.plot(value, y_fit)
    R2 = regression.score(X_test, y_test)

    # 修正列引用逻辑,填充符合条件的列数据
    if R2 >= cutoff:
        # 确保列名匹配空表的表头,填充对应数据
        if column in df_2.columns:
            df_2[column] = df[column].values
        # 若空表没有该列头,可选择添加(根据你的需求调整)
        else:
            df_2[column] = df[column].values

    plt.scatter(value, y)
    plt.xlabel(column)
    plt.grid()
    plt.show()
    
    print(f'For {column}, \n Coefficient of determination is;{R2}')
    print('fitting parameters:\n Slope = ', line.x[:1], '\n Intercept = ', line.x[1:2])

# 最后保存修改后的表到文件
df_2.to_csv('best_fit.csv', index=False)

关键修改说明

  1. 把df_2 = pd.read_csv('best_fit.csv')移到循环外部,避免每次循环重置已填充的数据
  2. 将错误的df[X.column]改为df[column],直接使用循环迭代的列名变量
  3. 替换df_2 = df[column].copy()为df_2[column] = df[column].values,在已有空表中填充对应列的数据,而非替换整个表
  4. 增加最后保存操作,确保修改后的结果写入文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:50:00