考虑以下数据帧:
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(如果你有很多行,这可能会给你带来可怕的性能).