gpt4 book ai didi

python - 对具有相同类别的多列进行标签编码

转载 作者:太空狗 更新时间:2023-10-30 02:25:37 25 4
gpt4 key购买 nike

考虑以下数据框:

import pandas as pd
from sklearn.preprocessing import LabelEncoder

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

当前输出:

   a  b  c
0 0 1 0
1 1 0 0

我的目标是通过传入我想共享分类值的列来使其输出类似这样的内容:

   a  b  c
0 0 1 2
1 1 0 2

最佳答案

通过 axis=1为每一行调用一次 LabelEncoder().fit_transform。(默认情况下,df.apply(func) 为每一列调用一次 func

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)

产量

   a  b  c
0 1 2 0
1 2 1 0

或者,您可以使用生成 category dtype 的数据并使用类别代码作为标签:

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)

也产生

   a  b  c
0 1 2 0
1 2 1 0

这应该快得多,因为它不需要为每一行调用一次 encoder.fit_transform(如果你有很多行,这可能会带来糟糕的性能)。

关于python - 对具有相同类别的多列进行标签编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613394/

25 4 0