【问题标题】:A given column is not a column of the dataframe Pandas给定的列不是数据框 Pandas 的列
【发布时间】:2021-05-25 13:19:09
【问题描述】:

我有以下拆分功能:

from typing import Tuple
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split

def split_dataframe(
    
    df: pd.DataFrame, 
    target_feature: str, 
    split_ratio: int = 0.2

) -> Tuple[pd.DataFrame, pd.DataFrame, np.ndarray, np.ndarray]:
     
    df_ = df.copy()
    
    X = df_.drop(target_feature, axis=1)
    y = df_[target_feature]
    
    encoder = LabelEncoder()
    y = encoder.fit_transform(y)
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = split_ratio)
    
    return  X_train, X_test, y_train, y_test

我使用以下方法拆分数据框:

X_train, X_test, y_train, y_test = split_dataframe(df, 'Банк')

我使用管道来转换 X_train 和 y_train

from sklearn.pipeline import Pipeline, FeatureUnion
from mlxtend.feature_selection import ColumnSelector
import category_encoders as ce

cat_pipe = Pipeline(
    [
        ('selector', ColumnSelector(categorical_features)),
        ('encoder', ce.one_hot.OneHotEncoder())
    ]
)

num_pipe = Pipeline(
    [
        ('selector', ColumnSelector(numeric_features)),
        ('scaler', StandardScaler())
    ]
)

preprocessor = FeatureUnion(
    transformer_list=[
        
        ('cat', cat_pipe),
        ('num', num_pipe)
    ]
)

new_df = pipe.fit_transform(X_train, y_train)

然后我得到 ValueError: A given column is not a column of the dataframe,特别是 KeyError: 'Банк'。我检查了在传递数据帧之前是否存在列以在训练和测试中拆分。如果我将 X = df_.drop(target_feature, axis=1) 删除到 X = df_ 一切正常,但目标功能仍在 X 中。

【问题讨论】:

  • onehotencode构造函数中尝试handle_unknown='ignore'
  • @SayandipDutta 谢谢你的回答。我试过了,还是报错
  • 我制作了一个带有名为“Банк”的列的示例数据框,它能够毫无错误地拆分它。请编辑以包含重现错误的df 数据框示例。

标签: python pandas


【解决方案1】:

我在pipe.fit_transform(X_train, y_train) 中发现了一个错误,我将其更改为preprocessor.fit_transform(X_train, y_train) 并且它起作用了

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 2021-06-30
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2019-04-08
    • 2023-03-06
    相关资源
    最近更新 更多