簡體   English   中英

如何將 sklearn 預處理器 fit_transform 與 pandas.groupby.transform 一起使用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM