首页 > 解决方案 > 如何在使用 minmaxscaler 时保持数据帧的索引?

问题描述

我正在尝试实现熵方法。所以,我需要在从字典转换的数据帧上使用 minmaxscaler。但是,因为我不知道 dict 的值中将使用多少个参数,所以在使用 DataFrame.from_dict() 时我无法命名所有行。结果,当我使用 MinMaxScaler 时,DataFrame 变成了一个 ndarray,并且 dict 的索引消失了。我怎么能保留索引?

import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler

dict = {'A':[89, 11], 'B':[80, 96], 'C':[97, 89], 'D':[90, 24], 'E': [100, 90]}

df = pd.DataFrame.from_dict(dict, orient='index')
print(df)
scaler = MinMaxScaler()
df = scaler.fit_transform(df[0:])
print(df)
yij = df.apply(lambda x: x / x.sum(), axis=0) # An error occurs here: AttributeError: 'numpy.ndarray' object has no attribute 'apply'
K = 1/np.log(len(df))
tmp = yij*np.log(yij)
tmp=np.nan_to_num(tmp)
ej = -K*(tmp.sum(axis=0))
wj = (1 - ej) / np.sum(1 - ej)
score = yij.apply(lambda x: np.sum(100 * x * wj), axis=1)
print(score)

标签: pythonpandasscikit-learn

解决方案


您可以使用:

df[:] = scaler.fit_transform(df)

它将用转换后的值替换所有值。此操作还保留行和列索引。


推荐阅读