数据标准化和离散化

在某些比较和评价的指标处理中经常需要去除数据的单位限制,将其转化为无量纲的纯数值,便于不同单位或量级的指标能够进行比较和加权。因此需要通过一定的方法进行数据标准化,将数据按比例缩放,使之落入一个小的特定区间。

一、标准化

1.0-1标准化

方法:将样本中的最大值、最小值记录下来,并通过max-min作为基数(即标准化后min=0、max=1)进行数据的归一化处理。

x = (x - min)/(max-min)

df = pd.DataFrame({'value1':np.random.rand(10)*10,'value2':np.random.rand(10)*100})
def f(data,*cols):df_n = data.copy()for col in cols:ma = df_n[col].max()  #每一列的最大值mi = df_n[col].min()  #每一列的最小值df_n[col+'_n'] = (df_n[col]-mi)/(ma -mi)  #计算各个样本标准化之后的值return df_ndf_n = f(df,'value1','value2')
df_n

 

2.Z-score标准化

z-score是一个数与样本平均数的差再除以标准差的过程 → z=(x-μ)/σ,其中x为某一具体数,μ为平均数,σ为标准差,Z值的量代表着原始数与母体平均值之间的距离,是以标准差为单位计算的。在原始数低于平均值时Z为负数,反之则为正数。数学意义:一个给定的数距离平均数多少个标准差。

在分类、聚类算法中,需要使用距离来度量相似性的时候,Z-score表现更好 。

df = pd.DataFrame({'value1':np.random.rand(10)*100,'value2':np.random.rand(10)*100})
def f(data,*cols):df_n = data.copy()for col in cols:u = df_n[col].mean()std = df_n[col].std()df_n[col+'_n'] = (df_n[col] - u)/stdreturn df_ndf_n = f(df,'value1','value2')
print(df_n)
u_n1 = df_n['value1_n'].mean()
std_n1 = df_n['value1_n'].std()
u_n2 = df_n['value2_n'].mean()
std_n2 = df_n['value2_n'].std()
print('标准化后value1的均值为%3.f,标准差为%.3f'%(u_n1,std_n1))
print('标准化后value2的均值为%3.f,标准差为%.3f'%(u_n2,std_n2))

 

案例应用

# 八类产品的两个指标value1,value2,其中value1权重为0.6,value2权重为0.4
# 通过0-1标准化,判断哪个产品综合指标状况最好
df = pd.DataFrame({"value1":np.random.rand(10) * 30,'value2':np.random.rand(10) * 100},index = list('ABCDEFGHIJ'))
#print(df.head())
#print('------')
# 创建数据"def data_norm(data,*cols):df_n = data.copy()for col in cols:ma = df_n[col].max()  #每一列的最大值mi = df_n[col].min()  #每一列的最小值df_n[col+'_n'] = (df_n[col]-mi)/(ma -mi)  #计算各个样本标准化之后的值return df_ndf_n1 = data_norm(df,'value1','value2')
# 进行标准化处理

df_n1['f'] = df_n1['value1_n'] * 0.6 + df_n1['value2_n'] * 0.4
df_n1.sort_values(by = 'f',inplace=True,ascending=False)
df_n1['f'].plot(kind = 'line', style = '--.k', alpha = 0.8, grid = True)
df_n1.head()

    

 

三、连续属性离散化

连续属性变换成分类属性,即连续属性离散化。

在数值的取值范围内设定若干个离散划分点,将取值范围划分为一些离散化的区间,最后用不同的符号或整数值代表每个子区间中的数据值

1.等宽法cut()

ages=[20,22,25,27,21,23,37,31,61,45,41,32]
bins = [18,25,35,60,100]   #按照18-25、25-35、35-60、60-100分为4个区间
age_cut = pd.cut(ages,bins)
print('分组结果:',age_cut,type(age_cut))  #分组后结果,显示每个值对应的区间
print('分组结果(代号表示):',age_cut.codes, type(age_cut.codes))  # 显示每个值对应的区间代号,结果为ndarray;可以查看里边的等级
print('分组区间:',age_cut.categories, type(age_cut.categories))  # 四个区间,结果为IntervalIndex
print('分组统计:\n',pd.value_counts(age_cut))  # 按照分组区间计数
print('-------')# 默认为左开右闭区间,right参数设置为False表示左闭右开区间
print(pd.cut(ages,[18,26,36,61,100],right=False)) 
print('-------')# 通过labels参数自定义区间名称
group_names=['Youth','YoungAdult','MiddleAged','Senior']
print(pd.cut(ages,bins,labels=group_names))
# 分组结果: [(18, 25], (18, 25], (18, 25], (25, 35], (18, 25], ..., (25, 35], (60, 100], (35, 60], (35, 60], (25, 35]]
# Length: 12
# Categories (4, interval[int64]): [(18, 25] < (25, 35] < (35, 60] < (60, 100]] <class 'pandas.core.arrays.categorical.Categorical'>
# 分组结果(代号表示): [0 0 0 1 0 0 2 1 3 2 2 1] <class 'numpy.ndarray'>
# 分组区间: IntervalIndex([(18, 25], (25, 35], (35, 60], (60, 100]],
#               closed='right',
#               dtype='interval[int64]') <class 'pandas.core.indexes.interval.IntervalIndex'>
# 分组统计:
#  (18, 25]     5
# (35, 60]     3
# (25, 35]     3
# (60, 100]    1
# dtype: int64
# -------
# [[18, 26), [18, 26), [18, 26), [26, 36), [18, 26), ..., [26, 36), [61, 100), [36, 61), [36, 61), [26, 36)]
# Length: 12
# Categories (4, interval[int64]): [[18, 26) < [26, 36) < [36, 61) < [61, 100)]
# -------
# [Youth, Youth, Youth, YoungAdult, Youth, ..., YoungAdult, Senior, MiddleAged, MiddleAged, YoungAdult]
# Length: 12
# Categories (4, object): [Youth < YoungAdult < MiddleAged < Senior]
输出结果

  

案例(使用上述例子中的ages、group_names和age_cut.codes)

df = pd.DataFrame({'ages':ages})
s = pd.cut(df['ages'],bins)  # 也可以 pd.cut(df['ages'],5),将数据等分为5份
df['label'] = s
cut_counts = s.value_counts(sort=False) 
# print(df)
# print(cut_counts)

plt.scatter(df.index,df['ages'],c = age_cut.codes)  #颜色按照codes分类
plt.grid()

 

2.等频法qcut()

等频法是将样本数据按照个数平均进行分组

data = np.random.randn(1000)
s = pd.Series(data)
cats = pd.qcut(s,4)  # 按四分位数进行切割,可以试试 pd.qcut(data,10)
print(cats.head())
print(cats.value_counts())# qcut → 根据样本分位数对数据进行面元划分,得到大小基本相等的面元,但并不能保证每个面元含有相同数据个数
# 也可以设置自定义的分位数(0到1之间的数值,包含端点) → pd.qcut(data1,[0,0.1,0.5,0.9,1])

plt.scatter(s.index,s,s = 15 ,c = pd.qcut(data,4).codes)  #用散点图表示,其中颜色按照codes分类
plt.xlim([0,1000])
plt.grid()
# 注意codes是来自于Categorical对象 
# 0    (-0.627, 0.0381]
# 1    (-3.348, -0.627]
# 2      (0.663, 3.403]
# 3    (-3.348, -0.627]
# 4    (-0.627, 0.0381]
# dtype: category
# Categories (4, interval[float64]): [(-3.348, -0.627] < (-0.627, 0.0381] < (0.0381, 0.663] < (0.663, 3.403]]
# (0.663, 3.403]      250
# (0.0381, 0.663]     250
# (-0.627, 0.0381]    250
# (-3.348, -0.627]    250
# dtype: int64
输出结果

 

转载于:https://www.cnblogs.com/Forever77/p/11380507.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391648.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

熊猫tv新功能介绍_熊猫简单介绍

熊猫tv新功能介绍Out of all technologies that is introduced in Data Analysis, Pandas is one of the most popular and widely used library.在Data Analysis引入的所有技术中&#xff0c;P andas是最受欢迎和使用最广泛的库之一。 So what are we going to cover :那么我…

关于sublime-text-2的Package Control组件安装方法,自动和手动

之前在自己的文章《Linux下安装以及破解sublim-text-2编辑器》的文章中提到过关于sublime-text-2的Package Control组件安装方法。 当时使用的是粘贴代码&#xff1a; 1import urllib2,os;pfPackage Control.sublime-package;ippsublime.installed_packages_path();os.makedirs…

上海区块链会议演讲ppt_进行第一次会议演讲的完整指南

上海区块链会议演讲pptConferences can be stressful even if you are not giving a talk. On the other hand, speaking can really boost your career, help you network, allow you to travel for (almost) free, and give back to others at the same time.即使您不讲话…

windows下Call to undefined function curl_init() error问题

本地项目中使用到curl_init()时出现Call to undefined function curl_init()的错误&#xff0c;去掉php.ini中的extensionphp_curl.dll前的分号还是不行&#xff0c;phpinfo()中无curl模块&#xff0c;于是上网搜索并实践了如下方法&#xff0c;成功&#xff1a; 在使用php5的c…

数据转换软件_数据转换

数据转换软件&#x1f4c8;Python金融系列 (&#x1f4c8;Python for finance series) Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you.警告 &#xff1a;这里没有神奇的配方或圣杯&#xff0c;尽管新世界可能为您…

leetcode 1047. 删除字符串中的所有相邻重复项(栈)

给出由小写字母组成的字符串 S&#xff0c;重复项删除操作会选择两个相邻且相同的字母&#xff0c;并删除它们。 在 S 上反复执行重复项删除操作&#xff0c;直到无法继续删除。 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 示例&#xff1a; 输入&#x…

spring boot: spring Aware的目的是为了让Bean获得Spring容器的服务

Spring Aware的目的是为了让Bean获得Spring容器的服务 //获取容器中的bean名称import org.springframework.beans.factory.BeanNameAware;//获得资源加载器&#xff0c;可以获得额外的资源import org.springframework.context.ResourceLoaderAware; package ch2.aware; import …

10张图带你深入理解Docker容器和镜像

【编者的话】本文用图文并茂的方式介绍了容器、镜像的区别和Docker每个命令后面的技术细节&#xff0c;能够很好的帮助读者深入理解Docker。这篇文章希望能够帮助读者深入理解Docker的命令&#xff0c;还有容器&#xff08;container&#xff09;和镜像&#xff08;image&#…

matlab界area_Matlab的数据科学界

matlab界area意见 (Opinion) My personal interest in Data Science spans back to 2011. I was learning more about Economies and wanted to experiment with some of the ‘classic’ theories and whilst many of them held ground, at a micro level, many were also pur…

javascript异步_JavaScript异步并在循环中等待

javascript异步Basic async and await is simple. Things get a bit more complicated when you try to use await in loops.基本的async和await很简单。 当您尝试在循环中使用await时&#xff0c;事情会变得更加复杂。 In this article, I want to share some gotchas to wat…

白盒测试目录导航

白盒测试目录导航&#xff08;更新中&#xff09; 2017-12-29 [1] 白盒测试&#xff1a;为什么要做白盒测试 [2] 白盒测试&#xff1a;理论基础 [3] 白盒测试实战&#xff08;上&#xff09; [4] 白盒测试实战&#xff08;中&#xff09; [5] 白盒测试实战&#xff08;下&#…

hdf5文件和csv的区别_使用HDF5文件并创建CSV文件

hdf5文件和csv的区别In my last article, I discussed the steps to download NASA data from GES DISC. The data files downloaded are in the HDF5 format. HDF5 is a file format, a technology, that enables the management of very large data collections. Thus, it is…

CSS仿艺龙首页鼠标移入图片放大

CSS仿艺龙首页鼠标移入图片放大&#xff0c;效果似乎没有js好。。。。。。 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>图片放大</title><style>*{padding:0;margin:0;}body{padding-…

leetcode 224. 基本计算器(栈)

给你一个字符串表达式 s &#xff0c;请你实现一个基本计算器来计算并返回它的值。 示例 1&#xff1a; 输入&#xff1a;s “1 1” 输出&#xff1a;2 示例 2&#xff1a; 输入&#xff1a;s " 2-1 2 " 输出&#xff1a;3 示例 3&#xff1a; 输入&#xff…

机械制图国家标准的绘图模板_如何使用p5js构建绘图应用

机械制图国家标准的绘图模板The theme for week #5 of the Weekly Coding Challenge is:每周编码挑战第5周的主题是&#xff1a; 创建绘图应用程序 (Creating a Drawing Application) This is the first application that we are building in the #weeklyCodingChallenge prog…

机器学习常用模型:决策树_fairmodels:让我们与有偏见的机器学习模型作斗争

机器学习常用模型:决策树TL; DR (TL;DR) The R Package fairmodels facilitates bias detection through model visualizations. It implements a few mitigation strategies that could reduce bias. It enables easy to use checks for fairness metrics and comparison betw…

高德地图如何将比例尺放大到10米?

2019独角兽企业重金招聘Python工程师标准>>> var map new AMap.Map(container, {resizeEnable: true,expandZoomRange:true,zoom:20,zooms:[3,20],center: [116.397428, 39.90923] }); alert(map.getZoom());http://lbs.amap.com/faq/web/javascript-api/expand-zo…

Android 手把手带你玩转自己定义相机

本文已授权微信公众号《鸿洋》原创首发&#xff0c;转载请务必注明出处。概述 相机差点儿是每一个APP都要用到的功能&#xff0c;万一老板让你定制相机方不方&#xff1f;反正我是有点方。关于相机的两天奋斗总结免费送给你。Intent intent new Intent(); intent.setAction(M…

如何在JavaScript中克隆数组

JavaScript has many ways to do anything. I’ve written on 10 Ways to Write pipe/compose in JavaScript, and now we’re doing arrays.JavaScript有许多方法可以执行任何操作。 我已经写了10种用JavaScript编写管道/组合的方法 &#xff0c;现在我们正在做数组。 1.传播…

leetcode 227. 基本计算器 II(栈)

给你一个字符串表达式 s &#xff0c;请你实现一个基本计算器来计算并返回它的值。 整数除法仅保留整数部分。 示例 1&#xff1a; 输入&#xff1a;s “32*2” 输出&#xff1a;7 解题思路 利用两个栈&#xff0c;一个记录操作数&#xff0c;一个记录操作符&#xff0c;…