![](/img/trans.png)
[英]How to use sklearn TfidfVectorizer fit_transform on two columns
[英]How to use sklearn preprocessor fit_transform with pandas.groupby.transform
如何将 sklearn 预处理 fit.transform() 与 pandas.groupby.transform 一起使用?
我在这里使用了这个有效的代码:
df.groupby('Category')['X1'].transform(lambda x: minmax_scale(x.astype(float)))
但是当我将其更改为下面的 MinMaxScaler() 方法时,它返回错误
使用 .fit_transform 方法时出错的代码
假设表只有 2 列:Category 和 X1
df.groupby('Category')['X1'].transform(lambda x: MinMaxScaler().fit_transform(x.values.reshape(-1,1)))
错误信息:
数据必须是一维的
但是,如果我不使用 .values.reshape(-1,1) 它会说
预期的二维数组,改为一维数组。 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据
我们不应该在熊猫上对 .apply / .transform 使用 fit_transform 方法吗?
编辑:更新了新的错误消息
您必须使用 MinMaxScaler 对象实例(添加括号)。 尝试这个:
lambda x: MinMaxScaler().fit_transform(x.values.reshape(-1,1))
如果要传递缩放范围,请将其传递给构造函数:
lambda x: MinMaxScaler(feature_range=(0, 10)).fit_transform(x.values.reshape(-1,1))
这是一个工作示例:
df = pd.DataFrame (np.random.randint(1,100,(10)),columns = ['a'])
df['a'].transform(lambda x: MinMaxScaler(feature_range=(0, 10)).
fit_transform(x.values.reshape(-1,1)))
array([[ 0. ],
[ 6.55172414],
[ 9.88505747],
[ 6.09195402],
[ 1.26436782],
[ 8.62068966],
[ 6.43678161],
[ 5.74712644],
[ 5.17241379],
[10. ]])
我刚刚找到了解决方案,即用 np.concatenate() 包装缩放器 解决方案类似于这里的线程: Pandas groupby in combine with sklean preprocessing continue
所以工作代码如下所示:
df.groupby('Category')['X1'].transform(
lambda x: np.concatenate(StandardScaler().fit_transform(x.values.reshape(-1,1))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.