4

Getting exception Exception: Data must be 1-dimensional

using NumPy in Python 3.7

Same code is working for others but not in my case. Bellow is my code please help

Working_code_in_diff_system

Same_code_not_working_in_my_system

import numpy as np 
from sklearn import linear_model
from sklearn.model_selection import train_test_split
import seaborn as sns
from sklearn import metrics
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv('./Data/new-data.csv', index_col=False)

x_train, x_test, y_train, y_test = train_test_split(df['Hours'], df['Marks'], test_size=0.2, random_state=42)

sns.jointplot(x=df['Hours'], y=df['Marks'], data=df, kind='reg')

x_train = np.reshape(x_train, (-1,1))
x_test = np.reshape(x_test, (-1,1))
y_train = np.reshape(y_train, (-1,1))
y_test = np.reshape(y_test, (-1,1))



#
print('Train - Predictors shape', x_train.shape)
print('Test - Predictors shape', x_test.shape)
print('Train - Target shape', y_train.shape)
print('Test - Target shape', y_test.shape)

Expected output should be

Train - Predictors shape (80, 1)

Test - Predictors shape (20, 1)

Train - Target shape (80, 1)

Test - Target shape (20, 1)

As output getting exception Exception: Data must be 1-dimensional

1
  • Your first jpg hints at the problem, reshape on a Series will be deprecated. Commented Jul 25, 2019 at 0:07

2 Answers 2

5

I think you need to call np.reshape on the underlying numpy array rather than on the Pandas series - you can do this using .values:

x_train = np.reshape(x_train.values, (-1, 1))

Repeat the same idea for the next three lines.

Or, if you are on a recent version of Pandas >= 0.24, to_numpy is preferred:

x_train = np.reshape(x_train.to_numpy(), (-1, 1))
Sign up to request clarification or add additional context in comments.

Comments

5

numpy.squeeze() removes all dimensions of size 1 from a NumPy array.

x_train = numpy.squeeze(x_train)

Converts a (80,1) array to (80,)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.