0
$\begingroup$

I am encoding two columns with index numbers 1 and 2 that is column number 2 and 3, using the following code, however, I am facing an error of invalid syntax : If I am using only 1 in the index value it is ok, please help on this.. how can I encode two columns simultaneously using OneHotEncoder here.

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(),[1:2])], remainder ='passthrough')
X = np.array(ct.fit_transform(X))

If I am using the following it is ok but I want to encode the other column as well.

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(),[1])], remainder ='passthrough')
X = np.array(ct.fit_transform(X))
$\endgroup$

1 Answer 1

1
$\begingroup$

Try:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers = [('encoder', OneHotEncoder(),[1,2])], remainder ='passthrough')
X = np.array(ct.fit_transform(X))

Note that you are passing [1:2] as the list of indices to apply the transformation on the ColumnTransformer but it should be [1,2]

$\endgroup$
3
  • $\begingroup$ : please note that I have changed that and I am facing the following errors now : Input contains NaN However, I have checked my data there is no NaN value. Do you have any input on this. Thanks. $\endgroup$
    – Sachin
    Commented Jul 24, 2021 at 16:35
  • $\begingroup$ The complete error is ValueError: Input contains NaN, infinity or a value too large for dtype('float32')so In your place I would check if I have an inf value somewhere $\endgroup$
    – Multivac
    Commented Jul 24, 2021 at 21:35
  • $\begingroup$ @ Julio Jesus : I have checked the dtype it is int64 , so there is no nan or inf value. While running the code it is showing For a sparse output, all columns should be a numeric or convertible to a numeric. $\endgroup$
    – Sachin
    Commented Jul 25, 2021 at 1:14

Your Answer

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

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