我有一个熊猫的数据框架,其中每一列都有不同的值范围。例如:
df:
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
知道我如何规范化这个数据框架的列,其中每个值都在0到1之间吗?
我想要的输出是:
A B C
1 1 1
0.765 0.5 0.7
0.8 0.7 0.18(which is 0.09/0.5)
我有一个熊猫的数据框架,其中每一列都有不同的值范围。例如:
df:
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
知道我如何规范化这个数据框架的列,其中每个值都在0到1之间吗?
我想要的输出是:
A B C
1 1 1
0.765 0.5 0.7
0.8 0.7 0.18(which is 0.09/0.5)
当前回答
基于这篇文章:https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range
您可以执行以下操作:
def normalize(df):
result = df.copy()
for feature_name in df.columns:
max_value = df[feature_name].max()
min_value = df[feature_name].min()
result[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
return result
你不需要一直担心你的价值观是积极的还是消极的。这些值应该很好地分布在0和1之间。
其他回答
下面的函数计算Z分数:
def standardization(dataset):
""" Standardization of numeric fields, where all values will have mean of zero
and standard deviation of one. (z-score)
Args:
dataset: A `Pandas.Dataframe`
"""
dtypes = list(zip(dataset.dtypes.index, map(str, dataset.dtypes)))
# Normalize numeric columns.
for column, dtype in dtypes:
if dtype == 'float32':
dataset[column] -= dataset[column].mean()
dataset[column] /= dataset[column].std()
return dataset
你的问题实际上是一个作用于列的简单变换:
def f(s):
return s/s.max()
frame.apply(f, axis=0)
或者更简洁:
frame.apply(lambda x: x/x.max(), axis=0)
要规范化一个DataFrame列,只使用本机Python。
不同的值会影响过程,例如图的颜色。
0到1之间:
min_val = min(list(df['col']))
max_val = max(list(df['col']))
df['col'] = [(x - min_val) / max_val for x in df['col']]
-1 ~ 1:
df['col'] = [float(i)/sum(df['col']) for i in df['col']]
OR
df['col'] = [float(tp) / max(abs(df['col'])) for tp in df['col']]
睡魔和普拉文给出的解决方案很好。唯一的问题是,如果你在数据帧的其他列中有分类变量,这种方法将需要一些调整。
我对这类问题的解决方案如下:
from sklearn import preprocesing
x = pd.concat([df.Numerical1, df.Numerical2,df.Numerical3])
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
x_new = pd.DataFrame(x_scaled)
df = pd.concat([df.Categoricals,x_new])
df_normalized = df / df.max(axis=0)