简体   繁体   English

如何将值从列表传递到 scikit 学习线性回归 model?

[英]How to pass values from list to scikit learn linear regression model?

I have imported values into python from a PostgreSQL DB.我已从 PostgreSQL DB 将值导入 python。

data = cur.fetchall()

The list is like this:-名单是这样的:-

[('Ending Crowds', 85, Decimal('50.49')), ('Salute Apollo', 73, Decimal('319.93'))][0] [('Ending Crowds', 85, Decimal('50.49')), ('Salute Apollo', 73, Decimal('319.93'))][0]

I need to give 85 as X & Decimal('50.49') as Y in LinearRegression model我需要在 LinearRegression model 中将 85 作为 X 和 Decimal('50.49') 作为 Y

Then I imported packages & class-然后我导入了包和类-

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression

I provide data & perform linear regression -我提供数据并执行线性回归 -

X = data.iloc[:, 1].values.reshape(-1, 1)  
Y = data.iloc[:, 2].values.reshape(-1, 1)  
linear_regressor = LinearRegression()  # create object for the class
linear_regressor.fit(X, Y)  # perform linear regression

I am getting the error- AttributeError: 'list' object has no attribute 'iloc'我收到错误- AttributeError: 'list' object has no attribute 'iloc'

I am a beginner to pyhon and started just 2 days back but need to do linear regression in python at my job for a project.我是 pyhon 的初学者,刚开始 2 天,但在我的项目工作中需要在 python 中进行线性回归。 I think iloc can't be used for list object.我认为 iloc 不能用于列表 object。 But, not able to figure out as to how to pass on X & Y values to linear_regressor.但是,无法弄清楚如何将 X 和 Y 值传递给 linear_regressor。 All the examples performing Linear Regression on sites are using.CSV.在站点上执行线性回归的所有示例都使用.CSV。 Please help me out.请帮帮我。

No, you can't use.iloc on 'list', it is for dataframe.不,您不能在“列表”上使用.iloc,它适用于 dataframe。 convert it into dataframe and try using.iloc将其转换为 dataframe 并尝试使用.iloc

Your solution is below, please approve it if it is correct.您的解决方案如下,如果正确请批准。 Because it's my 1st answer on StackOverflow因为这是我在StackOverflow上的第一个答案

import pandas as pd
from decimal import Decimal
from sklearn.linear_model import LinearRegression

#I don't know what that "[0]" in your list,because I haven't used data fetched from PostgreSQL. Anyway remove it first and store it in temp

temp=[('Ending Crowds', 85, Decimal('50.49')), ('Salute Apollo', 73, Decimal('319.93'))]

#I don't know it really needed or not
var = list(var)

data = []

#It is to remove "Decimal" word
for row in var:
    data.append(list(map(str, list(row))))
data=pd.DataFrame(data,columns=["no_use","X","Y"])
X=data['X'].values.reshape(-1, 1)
Y=data['Y'].values.reshape(-1, 1)
print(X,Y)

linear_regressor = LinearRegression()  # create object for the class
linear_regressor.fit(X, Y)  # perform linear regression

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

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