python - 如何在使用 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)
解决方案
您可以使用:
df[:] = scaler.fit_transform(df)
它将用转换后的值替换所有值。此操作还保留行和列索引。
推荐阅读
- android - Kotlin 编程语言中的 Android Studio 错误(RecyclerView 没有 LayoutManager)
- powershell - 多次并行运行同一任务 [POWERSHELL]
- android - 如何使用匕首将改造基本身份验证添加到网络模块?
- php - 获取由mysql查询填充的webform中所有复选框的状态
- python - 获取模型的 ID 并保存到 django 中其他模型的外键字段
- c# - Microsoft.ML 和 Xamarin
- ruby-on-rails - 在 Ruby 中,有没有一种可接受的方式将类拆分为更小的、可组合的 mixin(知道父级)?
- python - 在 selenium 中使用 xpath 定位 svg 时出错
- google-cloud-platform - Dialogflow 对话/来自 Webhook 的响应恢复
- c++ - GCC 中的 C++20 [[no_unique_address]] 的错误?