python - 如何在 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?
解决方案
train
是从 KFold 返回的训练数据的索引列表。您将train
作为访问列放入var[train]
将导致错误,因为索引值都不是 DataFrame 列。
IMO,将复杂的值设置为索引不是一个好主意,只需使用简单的值作为索引,例如
var.loc[count] = importances_index_desc
count += 1
推荐阅读
- c - 队列的外部类型定义
- git - 在 github 的 master 分支中管理多个项目
- r - show_modal_spinner 在 Rshiny 中生成输出之前立即消失
- javascript - 即使用户不拥有角色,机器人也会为用户分配角色
- scala - Scala 项目中的异常 java.lang.NoClassDefFoundError: scala/collection/SeqLike 不引用 SeqLike 类 - 为什么?
- javascript - Angular 表单的语音输入
- visual-studio-code - 为什么我在 linux 上找不到 vscode live share 扩展?
- php - 在 PHP 中显示带有序号后缀的日期
- django - 尝试前进或跳过 Django 中的视频时出错
- swift - 圆特定角的笔划/边框 SwiftUI