我正在使用管道预处理数据。这是我的代码。我想将字符串列转换为日期时间,并用np.nan
替换其他一些列的空字符串(''),“ N.A”。我正在尝试在流水线步骤中使用FunctionTransformer
。
df = pd.DataFrame({
'categoric1':['Apple', ' ', 'Cherry', 'Apple', 'Cherry', 'Cherry', 'Orange'],
'numeric1':[1, 2, 3, 4, 5, 6, 7],
'numeric2':[7,8,9,"N.A", np.nan, ' ', 12],
'date1': ['20001103','20011109', '19910929', '19920929', '20051107', '20081103', '20101105']})
cat_features = ['categoric1']
num_features = ['numeric1', 'numeric2']
date_features = ['date1']
print(df.head(7))
def replace_with_nan(X):
X_copy = X.copy()
X_copy[X_copy == ' '] = np.nan
X_copy[X_copy == 'N.A'] = np.nan
return X_copy.values
def square_values(X):
return X**2
def convert_to_datetime(df):
df['date1'] = pd.to_datetime(df['date1'], errors='raise') #df['date1'].astype(str) + "Z"
return df
cat_transformer = Pipeline(steps=[
('ft_replace_nan', FunctionTransformer(replace_with_nan, validate=False)),
('imputer', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
('encoder', OneHotEncoder(categories=[['Apple', 'Orange', 'Cherry']], handle_unknown='error'))
])
num_transformer = Pipeline(steps=[
('ft_replace_nan', FunctionTransformer(replace_with_nan, validate=False)),
# ('ft_square_values', FunctionTransformer(square_values, validate=False)), #Another FunctionTransformer -----1
('imputer', SimpleImputer(missing_values=np.nan, strategy='median')),
('scaler', StandardScaler())
])
date_transformer = Pipeline(steps=[
('convert_to_datetime', FunctionTransformer(convert_to_datetime, validate=False))
])
preprocessor = ColumnTransformer(remainder='passthrough', transformers = [
('num', num_transformer, num_features),
('cat', cat_transformer, cat_features),
('date', date_transformer, date_features)
])
# ft_fill_nan = FunctionTransformer(replace_with_nan, validate=False)
# transformed_data = ft_fill_nan.fit_transform(df)
# print(transformed_data)
# ft_convert_datetime = FunctionTransformer(convert_to_datetime, validate=False)
# transformed_data = ft_convert_datetime.fit_transform(df)
# print(transformed_data)
transformed_data = preprocessor.fit_transform(df)
print(transformed_data)
问题:
preprocessor.fit_transform(df)
时,
错误如下。您能帮我解决这个问题吗? #Another FunctionTransformer -----1
的值。可能吗?如果可以,怎么办?convert_to_datetime(df)
方法。我也想使其通用而不需要访问实际的date1
列。我该如何实现?答案 0 :(得分:1)
invalid type promotion
错误。 Sklearn尝试在内部使用numpy结构数组进行连接。解决方案是从日期中提取必要的功能,例如给定日期的月份。 您只需更改convert_to_datetime
def convert_to_datetime(data):
return data.apply(lambda x: [pd.to_datetime(date, format="%Y%m%d").month for date in x])
通过这种方式,您不必在函数内部对列名进行硬编码。
结果:
('ft_square_values', FunctionTransformer(lambda x: x*2, validate=False)), #Another FunctionTransformer -----1