Skip to content Skip to sidebar Skip to footer

Label Encoding Multiple Columns With The Same Category

Consider the following dataframe: import pandas as pd from sklearn.preprocessing import LabelEncoder df = pd.DataFrame(data=[['France', 'Italy', 'Belgium'], ['Italy', 'France', 'B

Solution 1:

Pass axis=1 to call LabelEncoder().fit_transform once for each row. (By default, df.apply(func) calls func once for each column).

import pandas as pd
from sklearn.preprocessing import LabelEncoder

df = pd.DataFrame(data=[["France", "Italy", "Belgium"], 
                        ["Italy", "France", "Belgium"]], columns=["a", "b", "c"])

encoder = LabelEncoder()

df = df.apply(encoder.fit_transform, axis=1)
print(df)

yields

ab  c
01201210

Alternatively, you could use make the data of category dtype and use the category codes as labels:

import pandas as pd

df = pd.DataFrame(data=[["France", "Italy", "Belgium"], 
                        ["Italy", "France", "Belgium"]], columns=["a", "b", "c"])

stacked = df.stack().astype('category')
result = stacked.cat.codes.unstack()
print(result)

also yields

ab  c
01201210

This should be significantly faster since it does not require calling encoder.fit_transform once for each row (which might give terrible performance if you have lots of rows).

Solution 2:

You can do this with pd.factorize.

df = df.stack()
df[:] = pd.factorize(df)[0]
df.unstack()

   a  b  c
0  0  1  2
1  1  0  2

In case you want to encode only some columns in the dataframe then:

temp = df[['a', 'b']].stack()
temp[:] = temp.factorize()[0]
df[['a', 'b']] = temp.unstack()

   a  b        c
001  Belgium
110  Belgium

Solution 3:

If the encoding order doesn't matter, you can do:

df_new = (         
    pd.DataFrame(columns=df.columns,
                 data=LabelEncoder()
                 .fit_transform(df.values.flatten()).reshape(df.shape))
)

df_new
Out[27]: 
   a  b  c
0  1  2  0
1  2  1  0

Solution 4:

Here's an alternative solution using categorical data. Similar to @unutbu's but preserves ordering of factorization. In other words, the first value found will have code 0.

df = pd.DataFrame(data=[["France", "Italy", "Belgium"],
                        ["Italy", "France", "Belgium"]],
                  columns=["a", "b", "c"])

# get unique values in order
vals = df.T.stack().unique()

# convert to categories and then extract codesfor col indf:
    df[col] = pd.Categorical(df[col], categories=vals)
    df[col] = df[col].cat.codes

print(df)

   a  b  c
0  0  1  2
1  1  0  2

Post a Comment for "Label Encoding Multiple Columns With The Same Category"