bhaskar indian
bhaskar indian

Reputation: 17

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

I have imported values into python from a PostgreSQL DB.

data = cur.fetchall()

The list is like this:-

[('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

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'

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. I think iloc can't be used for list object. But, not able to figure out as to how to pass on X & Y values to linear_regressor. All the examples performing Linear Regression on sites are using .CSV. Please help me out.

Upvotes: 0

Views: 1089

Answers (1)

Rajan
Rajan

Reputation: 757

No, you can't use .iloc on 'list', it is for dataframe. convert it into dataframe and try using .iloc

Your solution is below, please approve it if it is correct. Because it's my 1st answer on 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

Upvotes: 1

Related Questions