如何使用 pandas 对数据帧 python 中的多个列(但不是所有列)进行编码

how to encoding several column (but not all column) in dataframe python using pandas

我想使用两个数据帧(测试数据帧、训练数据帧)构建朴素贝叶斯模型

数据帧包含 13 列,但我只想在 5-6 列中将数据帧从 str 编码到 int 值。我怎样才能用一个代码做到这一点,以便可以直接编码 6 列,我遵循这个答案:

import pandas as pd
from sklearn.preprocessing import LabelEncoder

    df = pd.DataFrame({
    'colors':  ["R" ,"G", "B" ,"B" ,"G" ,"R" ,"B" ,"G" ,"G" ,"R" ,"G" ],
    'skills':  ["Java" , "C++", "SQL", "Java", "Python", "Python", "SQL","C++", "Java", "SQL", "Java"]
    })
    
    def encode_df(dataframe):
        le = LabelEncoder()
        for column in dataframe.columns:
            dataframe[column] = le.fit_transform(dataframe[column])
        return dataframe
    
    #encode the dataframe
    encode_df(df)

但它只编码 1 列,而我想要的是 6 列和 1 个代码。

您可以遍历列和 fit_transform

cols = ['col1', 'col2', 'col3', 'col4', 'col5', 'col6']

for col in cols:
    le = LabelEncoder()
    df[col] = le.fit_transform(df[col].astype('str'))
    
df

理想情况下,您希望对训练和测试数据集使用相同的转化体
为此你需要使用

for col in cols:
    le = LabelEncoder()
    le.fit(df_train[col].astype('str'))
    df_train[col] = le.transform(df_train[col].astype('str'))
    df_test[col] = le.transform(df_test[col].astype('str'))
        
df

你试过 apply() 了吗?

 le = LabelEncoder()
 df['colors'] = df['colors'].apply(lambda x: le.fit_transform(x))