1

I am working with a quarterly data matrix as such:

Qtrs,Y,X,,,
1Q11, 252.0 , 0.0166 ,1,0,0
2Q11, 212.4 , 0.0122 ,0, 1 ,0
3Q11, 425.9 , 0.0286 ,0,0, 1 
4Q11, 522.3 , 0.0322 ,0,0,0
1Q12, 263.2 , 0.0185 ,1,0,0
2Q12, 238.6 , 0.0131 ,0, 1 ,0
3Q12, 411.3 , 0.0270 ,0,0, 1 
4Q12, 538.4 , 0.0343 ,0,0,0
1Q13, 272.0 , 0.0180 ,1,0,0
2Q13, 212.3 , 0.0122 ,0, 1 ,0
3Q13, 405.2 , 0.0257 ,0,0, 1 
4Q13, 495.8 , 0.0308 ,0,0,0
1Q14, 264.5 , 0.0179 ,1,0,0
2Q14, 211.2 , 0.0116 ,0, 1 ,0

I am using the following code to read the csv data file in and fit the model:

import pandas as pd
from sklearn.linear_model import LinearRegression

data = pd.read_csv('C:/Filepath/Macro.csv')
regressor = LinearRegression()
regressor.fit(data['X'], data['Y'])

However the error I get when executing the code is:

ValueError: Found arrays with inconsistent numbers of samples: [ 1 14]

Any idea what basic error I am committing?

1 Answer 1

1

sklearn models expect the X data (the predictor variables) to be 2D data of shape (n_samples, n_features).
So in this case, you can pass the X data as a dataframe by doing data[['X']] instead of data['X']:

In [24]: regressor.fit(data[['X']], data['Y'])
Out[24]: LinearRegression(copy_X=True, fit_intercept=True, normalize=False)

As an explanation of the double square brackets: data[['X']] is the pandas way to specify you want to select a subset of your dataframe corresponding to this list of column names (in your case a list of one element), instead of data['X'] which just returns that one column as a series:

In [27]: data['X'].shape
Out[27]: (14L,)

In [28]: data[['X']].shape
Out[28]: (14, 1)
4
  • Thanks @Joris. Just to clarify the answer, if I had multiple predictor variables (say the next 3 columns after X), could I use [X] instead of [[X]]. Put another way, how would I include the next 3 predictor variable columns as predictors?
    – ZJAY
    Jan 18, 2016 at 17:11
  • Why not also include the Y variable in double brackets [[Y]]?
    – ZJAY
    Jan 18, 2016 at 17:14
  • On your first question, you can use the same syntax (list of column names within the [] getter), but then with multiple columns, which gives: data[['col1', 'col2', 'col3']]
    – joris
    Jan 18, 2016 at 17:20
  • On your second question: that would also work (you can try), but is not needed because y is expected to be one-dimensional if you have one target variable (so sklearn will recognize this case)
    – joris
    Jan 18, 2016 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.