首页 > 解决方案 > 如何在 for 循环中更新熊猫数据框中的值?

问题描述

我正在尝试制作一个可以在每次迭代后存储变量 coeff 值的数据框。我能够在每次迭代后绘制图表。但是当我尝试在每次迭代后将值插入数据框中时。

我收到这个错误。

[Int64Index([ 3169, 3170, 3171, 3172, 3173, 3174, 3175, 3176, 3177,\n 3178,\n ...\n 31671, 31672, 31673, 31674, 31675, 3163676, 31677, , 31679,\n
31680],\n dtype='int64', length=28512)] 在 [列]

这是我使用的代码:

from sklearn.model_selection import KFold

kf = KFold(n_splits=10)
cvlasso= Lasso(alpha=0.001)
count = 1

var = pd.DataFrame()


for train, _ in kf.split(X, Y):
    cvlasso.fit(X.iloc[train, :], Y.iloc[train])
    importances_index_desc = cvlasso.coef_
    feature_labels = list(X.columns.values)
    importance = pd.Series(importances_index_desc, feature_labels)
    plt.figure()
    plt.bar(feature_labels, importances_index_desc)
    plt.xticks(feature_labels, rotation='vertical')
    plt.ylabel('Importance')
    plt.xlabel('Features')
    plt.title('Fold {}'.format(count))
    count = count + 1
    var[train] = importances_index_desc

plt.show()

还有一件事,我的数据集中总共有 33000 个观察值,但在循环结束时,训练值是 28512?有谁知道为什么火车价值不是33000?

标签: pythonpandasdataframe

解决方案


train是从 KFold 返回的训练数据的索引列表。您将train作为访问列放入var[train]将导致错误,因为索引值都不是 DataFrame 列。

IMO,将复杂的值设置为索引不是一个好主意,只需使用简单的值作为索引,例如

var.loc[count] = importances_index_desc
count += 1

推荐阅读