简体   繁体   English

迭代/循环所有列

[英]iterate/loop over all columns

I'm new to pandas, still learning and I wanted to ask if using iloc[:,1] is locating the column by index, how can I get all the columns if I want to get all the columns from 1-10?我是iloc[:,1] ,仍在学习,我想问一下使用iloc[:,1]是否按索引定位列,如果我想获取 1-10 中的所有列,如何获取所有列? Does it has to way to iterate over all the columns or can be only done using iloc[] one by one?它是否必须遍历所有列,还是只能使用iloc[]一一完成? Because I wanted to predict value of y (one column) with all the variables in x for eg:col[0] to col[9].因为我想用 x 中的所有变量来预测 y(一列)的值,例如:col[0] 到 col[9]。 I've tried iteritems() beforehand but it says我事先尝试过iteritems()但它说

Series' objects are mutable, thus they cannot be hashed系列的对象是可变的,因此它们不能被散列

Code:代码:

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')

Maybe try也许试试

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

This gives you a dataframe with columns 0-9 and then you can process each column in a for loop.这为您提供了一个包含 0-9 列的数据框,然后您可以在 for 循环中处理每一列。

Alternatively, you can get a name list of all columns by calling或者,您可以通过调用获取所有列的名称列表

X_test.columns

Then you can iterate the list and access each column by calling然后你可以迭代列表并通过调用访问每一列

X_test[your_column_name]

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

X_test[X_test.columns[:10]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM