遍历/循环所有列

时间:2020-10-30 13:13:58

标签: python pandas linear-regression

我是熊猫的新手,仍然在学习,我想问一下是否使用iloc[:,1]来按索引查找列,如果我想从1-10中获取所有列,如何获取所有列?它是否必须遍历所有列,还是只能使用iloc[]一一完成?因为我想用x中的所有变量来预测y的值(一列),例如:col [0]至col [9]。我已经尝试过iteritems(),但是它说

系列的对象是可变的,因此不能被散列

代码:

regrmodel = linear_model.LinearRegression()
print("Y train",y_train)
regrmodel.fit(X_train, y_train)

y_test_pred = regrmodel.predict(X_test)
y_test_pred = pd.Series(y_test_pred)
y_test_pred.index = y_test.index

plt.scatter(X_test.iloc[:,9], y_test, color='red',label='Actual data')
plt.scatter(X_test.iloc[:,9], predicted_test_data, color='green',label='Predicted data')

2 个答案:

答案 0 :(得分:0)

也许尝试

X_test.iloc[:,range(0,10)]

这为您提供了一个具有0至9列的数据框,然后您可以在for循环中处理每一列。

或者,您可以通过调用获取所有列的名称列表

X_test.columns

然后您可以遍历列表并通过调用来访问每一列

X_test[your_column_name]

答案 1 :(得分:0)

这将为您提供一个新的数据框,其中包含X_test的前十列:

X_test[X_test.columns[:10]]
相关问题