我想规范化我的数据集中的所有数值。
我已将整个数据集放入一个熊猫数据框。
到目前为止,我要这样做的代码:
for column in numeric: #numeric=df._get_numeric_data()
x_array=np.array(df[column])
normalized_X=preprocessing.normalize([x_array])
但是我如何验证这是正确的?我尝试在归一化之前以及在for循环前后添加这段代码后为其中一列绘制直方图:
x=df['Below.Primary'] #Below.Primary is one of my column names
plt.hist(x, bins=45)
蓝色直方图在for循环之前,橙色在之后。我的总代码如下所示:
ln[21] plt.hist(df['Below.Primary'], bins=45)
ln[22] for column in numeric:
x_array=np.array(df[column])
normalized_X=preprocessing.normalize([x_array])
x=df['Below.Primary']
plt.hist(x, bins=45)
我没有看到规模缩小。我做错了什么?如果不正确,有人可以指出正确的方法来做我想做的事吗?
尝试使用此:
scaler = preprocessing.StandardScaler()
df[col] = scaler.fit_transform(df[col])
您必须在迭代时将normalized_X设置为相应的列。
for column in numeric:
x_array=np.array(df[column])
normalized_X=preprocessing.normalize([x_array])
df[column]= normalized_X #Setting normalized value in the column
x=df['Below.Primary']
plt.hist(x, bins=45)
首先有一些一般的事情。
ndarray
的熊猫系列,因此您只需将ndarray
与Series.values
一起请求即可,而无需调用np.array()
。 See this page on the Pandas Series。我建议为此使用sklearn.preprocessing.Normalizer。
import pandas as pd
from sklearn.preprocessing import Normalizer
### Without the for loop (recommended)
# this version returns array
normalizer = Normalizer()
normalized_values = normalizer.fit_transform(df[numeric])
# normalized_values is a 2D array which is useful
# for many applications
# to convert back to DataFrame
df = pd.DataFrame(normalized_values, columns = numeric)
### with the for-loop (not recommended)
for column in numeric:
x_array = df[column].values.reshape(-1,1)
df[column] = normalizer.fit_transform(x_array)