[Python] How to use ColumnTransformer for categorical data?

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to preprocess data.

    data = {'Country':['Germany', 'Turkey', 'England', 'Turkey', 'Germany', 'Turkey'],
    'Age':['44', '32', '27', '29', '31', '25'],
    'Salary':['5400', '8500', '7200', '4800', '6200', '10850'],
    'Purchased':['yes', 'yes', 'no', 'yes', 'no', 'yes']}
    df = pd.DataFrame(data)
    X = df.iloc[:,0].values


    Expected result is like this:

    |---|---|---|----|-------|---|
    | 1 | 0 | 0 | 44 | 5400 | 1 |
    | 0 | 1 | 0 | 32 | 8500 | 1 |
    | 0 | 0 | 1 | 27 | 7200 | 0 |
    | 0 | 1 | 0 | 29 | 4800 | 1 |
    | 1 | 0 | 0 | 31 | 6200 | 0 |
    | 0 | 1 | 0 | 25 | 10850 | 1 |


    Here is the code that failed.

    from sklearn.preprocessing import OneHotEncoder
    from sklearn.compose import ColumnTransformer
    ct = ColumnTransformer([("city_category", OneHotEncoder(dtype='int'), [0])], remainder="passthrough")
    X = ct.fit_transform(X)


    Output:

    IndexError: tuple index out of range


    I want to learn that how to use ColumnTransformer function in this situations?

    Continue reading...

Compartilhe esta Página