清理数据 python

内容 (Content)

  1. Identifying data types识别数据类型
  2. Fixing the rows and columns固定行和列
  3. Imputing/removing missing values插补/删除缺失值
  4. Handling outliers处理异常值
  5. Standardising the values标准化值
  6. Fixing invalid values修正无效值
  7. Filtering the data过滤数据

1.识别数据类型 (1. Identifying Data Types)

  1. Find Categorical Data查找分类数据

list(df.columns[df.dtypes == ‘object’])

列表(df.columns [df.dtypes =='object'])

But, Categorical data can exist in Numerical format. eg. , days of a month, months(1–12), waist-size (24–38).

但是,分类数据可以数字格式存在。 例如。 ,每月的某几天,几个月(1–12),腰围(24–38)。

2. Distinguish between Numerical and Categorical Data

2.区分数值数据和分类数据

df.nunique().sort_values()

df.nunique()。sort_values()

Categorical — The count of unique values should be 30 or less.

分类-唯一值的计数应小于或等于30。

对数值数据进行运算 (Perform operations on numerical data)

Correlations — should only be done on numeric variables.

关联-仅应在数字变量上进行。

uniqueCount = df.nunique()

uniqueCount = df.nunique()

numerical_columns = list (uniqueCount [ uniqueCount > 30 ].keys())

numeric_columns =列表(uniqueCount [uniqueCount> 30] .keys())

df[numerical_columns] .corr()

df [numerical_columns] .corr()

对数值数据进行可视化 (Perform Visualisations on numerical data)

Scatter plot should always be feed with numerical data each side.

散点图应始终在两侧馈送数值数据。

2.固定行和列 (2. Fixing the rows and columns)

2.1检查格式 (2.1 Check Formatting)

  1. Check the file format检查文件格式

pd.read_csv() / pd.read_tsv()

pd.read_csv()/ pd.read_tsv()

2. Check the separator type

2.检查分隔符类型

pd.read_csv(sep = ‘|’)

pd.read_csv(sep ='|')

2.2固定行 (2.2 Fixing rows)

  1. Ignore irrelevant rows — Rows other than the column name headers , use skiprows = 2

    忽略不相关的行-列名标题以外的行,请使用skiprows = 2

  2. Delete summary rows — We derive such insights from dataset, hence not required.删除摘要行-我们从数据集中获得此类见解,因此不是必需的。
  3. Delete extra rows — column number indicator, subsection, new page.删除多余的行-列号指示符,小节,新页面。

df = df.loc[‘condition’]

df = df.loc ['condition']

2.3固定柱 (2.3 Fixing columns)

  1. Add column names if missing.如果缺少,请添加列名称。

df.columns.values[i] = ‘Column_name’

df.columns.values [i] ='列名'

2. Rename columns consistently: Abbreviations, encoded columns.

2.一致地重命名列:缩写,编码列。

df.rename(columns = {‘old_name’ : ‘new_name’} )

df.rename(columns = {'old_name':'new_name'})

3. Align misaligned columns -> Manual fix on file.

3.对齐未对齐的列->手动修复文件。

4. Delete columns having less analytical value. Like name, (system-generated)id columns.

4.删除分析值较小的列。 像名称一样,(系统生成的)id列。

df.drop(columns = [‘col1’, ‘col2’])

df.drop(columns = ['col1','col2'])

df.drop([‘col1’, ‘col2’], axis = 1)

df.drop(['col1','col2'],轴= 1)

5. Split/merge columns to get more understandable data.

5.拆分/合并列以获取更多可理解的数据。

df[‘avg’] = (df[‘M1’] + df[‘M2’]) /2 ;

df ['avg'] =(df ['M1'] + df ['M2'])/ 2;

df[‘fullname’] = df[‘firstname] + ‘ ‘ + df[lastname]

df ['fullname'] = df ['firstname] +''+ df [lastname]

3.插补/删除缺失值 (3. Imputing/removing missing values)

3.1用空值替换空值 (3.1 Replace Empty values with Nulls)

Need to replace the empty strings or object NA,XX with nan

需要用nan替换空字符串或对象NA,XX

df.replace(r’^\s*$’, np.NaN, regex=True)

df.replace(r'^ \ s * $',np.NaN,regex = True)

df.replace(r’NA’, np.NaN, regex=True)

df.replace(r'NA',np.NaN,regex = True)

df.replace(r’XX’, np.NaN, regex=True)

df.replace(r'XX',np.NaN,regex = True)

3.2检查空值 (3.2 Check Nulls)

  1. List null values列出空值

df.columns[df.isna().any()].tolist()

df.columns [df.isna()。any()]。tolist()

2. Check the Percentage of nulls

2.检查空值百分比

df.isnull().sum()/len(df)*100).sort_values(ascending = False)

df.isnull()。sum()/ len(df)* 100).sort_values(升序= False)

3. Profilers — Check Null value visualizations.

3.事件探查器—检查“空值”可视化。

3.3删除行/列 (3.3 Removing Rows/Columns)

  1. Removing the outlier data删除异常数据

df = df[df[‘field1’] < Outliers]

df = df [df ['field1'] <离群值]

2. Removing data if the target value is missing

2.如果缺少目标值,则删除数据

df1 = df[~df[‘target-value’].isnull()].copy()

df1 = df [〜df ['target-value']。isnull()]。copy()

3. High Percentage of nulls

3.高百分比的空值

df.drop(columns = [‘col1’, ‘col2’]) / df.drop([‘col1’, ‘col2’], axis = 1)

df.drop(columns = ['col1','col2'])/ df.drop(['col1','col2'],轴= 1)

df = df.loc[:, df.isnull().mean() < .95]

df = df.loc [:, df.isnull()。mean()<.95]

3.4.1缺失值类型 (3.4.1 Missing Values Types)

MCAR: It stands for Missing Completely At Random. The reason behind a missing value is not dependent on any other feature.

MCAR :代表随机完全丢失。 缺少值的原因不依赖于任何其他功能。

MAR: It stands for Missing At Random. The reason behind a missing value may be associated with some other features.

MAR :代表“随机失踪”。 缺少值的原因可能与某些其他功能有关。

MNAR: It stands for Missing Not At Random. There is a specific reason behind a missing value.

MNAR :代表不随机丢失。 缺少值背后有特定原因。

3.4.2缺失值处理 (3.4.2 Missing Values Treatment)

df.[field].fillna() → fill null values

df。[field] .fillna() →填充空值

  1. Replacing all nulls with zeros →用零替换所有空值→

df.fillna(0)

df.fillna(0)

2. Imputing values using Mean, Median, Mode

2.使用均值,中位数,众数估算值

Mean — continuous, if data set does not have outliers.

均值-连续(如果数据集没有异常值)。

df[‘field1’].mean()

df ['field1']。mean()

Median — Has outliers

中位数-有异常值

df[‘field1’].median()

df ['field1']。median()

Mode — Max occurrence value, categorical.

模式-最大发生值(绝对)。

df[‘field1’].mode()[0]

df ['field1']。mode()[0]

3. Fill with a relevant value by looking at other columns of the same row.

3.通过查看同一行的其他列来填充相关值。

df[‘field’] = df.apply(lambda x : transform(x), axis =1)

df ['field'] = df.apply(lambda x:transform(x),axis = 1)

4.处理异常值 (4. Handling outliers)

Q3 = np.percentile(df[‘field1’], 75)

Q3 = np.percentile(df ['field1'],75)

Q1 = np.percentile(df[‘field1’], 25)

Q1 = np.percentile(df ['field1'],25)

IQR = Q3 — Q1

IQR = Q3-Q1

Outliers = Q3 + 1.5 * IQR

离群值= Q3 + 1.5 * IQR

df = df[df[‘field1’] < Outliers] df[‘field1’].plot(kind=’box’)

df = df [df ['field1'] <离群值] df ['field1']。plot(kind ='box')

5.标准化值 (5. Standardising the values)

  1. Standardise Precision — for better presentation of data. e.g. change 4.5312341 kg to 4.53 kg.

    标准化精度 -更好地呈现数据。 例如,将4.5312341公斤更改为4.53公斤。

df[‘field’] = df[‘field’] .apply(lambda x : round(x,2))

df ['field'] = df ['field'] .apply(lambda x:round(x,2))

2. Scale Values/Standardise Units — Ensure all observations under one variable are expressed in a common and consistent unit.

2. 标度值/标准化单位 -确保在一个变量下的所有观察值均以相同且一致的单位表示。

df[‘field’] = df[‘field’] .apply(lambda x : transform(x))

df ['field'] = df ['field'] .apply(lambda x:transform(x))

3. Standardise Format — It is important to standardise the format of other elements such as date and name. e.g., change 23/10/16 to 2016/10/23.

3. 标准化格式—标准化其他元素(例如日期和名称)的格式很重要。 例如,将23/10/16更改为2016/10/23。

df[‘field1’] = pd.to_datetime(df[‘field1’], format = ’%d%b%Y:%H:%M:%S. %f’)

df ['field1'] = pd.to_datetime(df ['field1'],format ='%d%b%Y:%H:%M:%S。%f')

strftimes — Check the date format from this link.

strftimes-从此链接检查日期格式。

4. Standardise Case — String variables may take various casing styles, e.g. FULLCAPS, lowercase, Title Case, Sentence case, etc.

4. 标准化大小写 —字符串变量可以采用各种大小写样式,例如FULLCAPS,小写字母,标题大小写,句子大小写等。

df[‘field1’] = df[‘field1’].str.title()

df ['field1'] = df ['field1']。str.title()

5. Remove Characters — Remove extra characters such as common prefixes/suffixes, leading/trailing/multiple spaces.

5. 删除字符 -删除多余的字符,例如常见的前缀/后缀,前导/后缀/多个空格。

df[‘field1’] = arrests[‘field1’].str.replace(‘$’, ‘’ )

df ['field1'] =逮捕['field1']。str.replace('$','')

df[‘field1’] = df[‘field1’].str.strip()

df ['field1'] = df ['field1']。str.strip()

6.修正无效值 (6. Fixing invalid values)

  1. Encode unicode properly — In case the data is being read as junk characters, try to change the encoding.

    正确编码unicode-如果数据被读取为垃圾字符,请尝试更改编码。

df= pd.read_csv(‘file.csv’,encoding =’cp1252')

df = pd.read_csv('file.csv',encoding ='cp1252')

2. Convert incorrect data types — Change the incorrect data types to the correct data types for ease of analysis.

2. 转换不正确的数据类型—将不正确的数据类型更改为正确的数据类型,以便于分析。

df[‘field1’] = df[‘field1’].astype(int)

df ['field1'] = df ['field1']。astype(int)

df[toNumFieldsArray] = df[toNumFieldsArray].apply(pd.to_numeric, errors=’coerce’,axis=1)

df [toNumFieldsArray] = df [toNumFieldsArray] .apply(pd.to_numeric,errors ='coerce',axis = 1)

3. Correct values that lie beyond the range — If some values lie beyond the logical range.

3. 纠正超出范围的-如果某些值超出逻辑范围。

df.[‘field1’].describe() -> min/max values

df。['field1']。describe()->最小值/最大值

df.[‘field1’].plot(kind = ‘box’)

df。['field1']。plot(kind ='box')

4. Correct values that do not belong to the list — Remove values that do not belong to a list. eg. a data set of blood groups of individuals, strings ‘E’ and ‘F’ are invalid values.

4. 纠正不属于列表的删除不属于列表的值。 例如。 在个人血型数据集中,字符串“ E”和“ F”是无效值。

df[‘field’].value_counts()

df ['field']。value_counts()

5. Fix incorrect structure — Values that do not follow a defined structure can be removed Eg. a phone number of 12 digits is an invalid value.

5. 修复错误的结构-可以删除不遵循定义的结构的值,例如。 12位电话号码是无效值。

df[‘len’] = df[‘filed1’].apply(lambda x : len(str(x)))

df ['len'] = df ['filed1']。apply(lambda x:len(str(x)))

6. Validate internal rules — Internal rules, if present, should be correct and consistent. eg. a product’s date of delivery cannot be less than date of purchase.

6. 验证内部规则-内部规则(如果存在)应正确且一致。 例如。 产品的交货日期不能少于购买日期。

df[df[‘field1’]>df[‘field2’]]

df [df ['field1']> df ['field2']]

7.过滤数据 (7. Filtering the data)

  1. Deduplicate data — Remove identical rows and rows in which some columns are identical.

    重复数据删除删除相同的行和某些列相同的行。

df.drop_duplicates(subset =”field1",keep = first/last, inplace = True)

df.drop_duplicates(subset =“ field1”,keep = first / last,inplace = True)

2. Filter rows — Filter rows by segment and date period to obtain only rows that are relevant to the analysis.

2. 筛选行—按细分和日期期间筛选行,以仅获取与分析相关的行。

df = df.loc[‘condition’]

df = df.loc ['condition']

3. Filter columns — Filter columns that are relevant to the analysis.

3. 过滤器列-与分析相关的过滤器列。

df_derived = df.filter(regex = “^COMMON_EXP”, axis = 1)

df_derived = df.filter(regex =“ ^ COMMON_EXP”,轴= 1)

4. Binning Data — converting a numerical data to categorical.

4. 合并数据 -将数字数据转换为分类数据。

df[‘field-group’] = pd.cut(df[‘field1’] , bins=np.linspace (min,max,bin_count))

df ['field-group'] = pd.cut(df ['field1'],bins = np.linspace(min,max,bin_count))

翻译自: https://medium.com/@duarohan18/data-cleaning-techniques-using-python-b6399f2550d5

清理数据 python


http://www.taodudu.cc/news/show-4060237.html

相关文章:

  • Java中String使用及分析(UTF-8简单编码/解码器实现)
  • 使用Go清理数据:第1部分
  • [源码]UnicodeTOGB,能够将Unicode串转换成GB码,方便开发。
  • C++20 实现字符串类型的转换操作
  • 关于 Unicode 每个程序员应该知道的 5 件事
  • UnicodeTOGB,能够将Unicode串转换成GB码,方便开发。
  • UnicodeTOGB,能够将Unicode串转换成GB码
  • python3 unicode_关于你不想知道的所有Python3 unicode特性
  • MySQL把性别编码转换成名字_两种转换mysql数据编码的方法
  • 【字符编码转换】使用iconv
  • 麻省理工学院——人工智能公开课总结02
  • 麻省理工大学公开课学习笔记【1、算法分析】
  • 麻省理工学院公开课:信号与系统:模拟与数字信号处理 调幅演示
  • 麻省理工大学公开课笔记:算法导论(一)——引言
  • 麻省理工大学公开课笔记:算法导论(二)——课程简介及算法分析
  • 20210531
  • Linux第一个正式版本,你安装的第一个Linux系统是什么版本的,成功没有啊?
  • 计算机教学模式有待创新,计算机软件教学中教学评价模式的创新与探索
  • 为什么要避免使用malloc()和free()函数?
  • linux 没有dll文件,求助 hai.dll文件丢失 在线等
  • html给图片坐标没连接,4-HTML中的 a, img/标签使用及锚点,路径相关
  • html文本打印lt;igt;字段,6-HTMLlt; formgt;表单标签和属性
  • 广度优先遍历搜索的最通俗介绍,如何实现广度优先搜索算法?广度优先遍历搜索可用于哪些行业?
  • python实现合并多个excel中同名的sheet
  • 知乎张瑞: 浅析机器学习理论与实践 | 业界对话
  • C++ Primer 第四章学习 —— “表达式”
  • springboot医疗管理系统 毕业设计-附源码015221
  • CCIE-重认证-300-410-补充题库-必须的哟
  • linux搭建tht框架,教程 中标麒麟linux硬盘安装图解
  • C语言系列(5) --- C语言文件的操作

清理数据 python_使用python的数据清理技术相关推荐

  1. python和r语言做大数据_R和python大数据

    数据科学界华山论剑:R与Python巅峰对决 如果你是数据分析领域的新兵,那么你一定很难抉择--在进行数据分析时,到底应该使用哪个语言,R还是Python?在网络上,也经常出现诸如"我想学习 ...

  2. python爬虫怎么爬同一个网站的多页数据-如何用Python爬数据?(一)网页抓取

    如何用Python爬数据?(一)网页抓取 你期待已久的Python网络数据爬虫教程来了.本文为你演示如何从网页里找到感兴趣的链接和说明文字,抓取并存储到Excel. 需求 我在公众号后台,经常可以收到 ...

  3. python与excel做数据可视化-用Python进行数据可视化的10种方法

    原标题:用Python进行数据可视化的10种方法 2015-11-19 关于转载授权 大数据文摘作品,欢迎个人转发朋友圈,自媒体.媒体.机构转载务必申请授权,后台留言"机构名称+转载&quo ...

  4. python写入excel表格数据绘制图表,Python对数据写入Execl文件并生成图表

    Python对数据写入Execl文件并生成图表 需求: 为了做测试或者对爬虫程序爬取数据进行分析汇总,我们时常会将数据生成报表,但是如果我们想将报表生成在Excel中,这时候就可以借助xlsxwrit ...

  5. 大数据入门选择python大数据么?现在程序员都是喜欢这个

    Python是适合做大数据分析的计算机语言吗?如今是一个大数据时代,通过数据分析,我们可以得到任何我们想知道的事情,充分挖掘数据的价值.之前有人说过JAVA语言是最适合做数据分析的计算机编程语言之一, ...

  6. 数据之路 - Python爬虫 - 数据存储

    一.文件存储 1.文件打开方式 文件打开方式 说明 r 以只读方式打开文件.文件的指针将会放在文件的开头.这是默认模式 rb 以二进制只读方式打开一个文件.文件指针将会放在文件的开头 r+ 以读写方式 ...

  7. 处理100万条数据 python_使用 Python 处理3万多条数据只要几秒钟

    应用场景:工作中经常遇到大量的数据需要整合.去重.按照特定格式导出等情况.如果用 Excel 操作,不仅费时费力,还不准确,有么有更高效的解决方案呢? 本文以17个 txt 文本,3万多条数据为例,使 ...

  8. 如何用python画数据图-利用Python绘制数据的瀑布图的教程

    介绍 对于绘制某些类型的数据来说,瀑布图是一种十分有用的工具.不足为奇的是,我们可以使用Pandas和matplotlib创建一个可重复的瀑布图. 在往下进行之前,我想先告诉大家我指代的是哪种类型的图 ...

  9. 同花顺数据python_同花顺上市公司简单数据爬取

    针对读者:入门 语言:python 目标:爬取上市公司的股票代码.公司简称.公司全称.创办日期.上市日期.历史年度营收数据.总市值. 结果展示 { "_id" : { " ...

  10. python大数据免费_用python做大数据

    不学Python迟早会被淘汰?Python真有这么好的前景? 最近几年Python编程语言在国内引起不小的轰动,有超越Java之势,本来在美国这个编程语言就是最火的,应用的非常非常的广泛,而Pytho ...

最新文章

  1. WAIC 2021 | 中国惠普周信宏:AI基础设施——边缘计算演进及趋势
  2. Nature发文:深度学习系统为什么这么好骗?
  3. 如何使用gensim来加载和使用词向量模型word2vec
  4. 给力的 Google HTML5 训练营(HTML5 DragDrop 拖拽、FileRea...
  5. VS2010运行类向导提示“未实现该方法或操作”
  6. Android studio如何使用SVN进行版本控制?
  7. 数据库设计之从0到1 教你如何设计E-R图
  8. Python之区块链入门,揭秘比特币
  9. 计算机基础- -认识汇编
  10. Machine Learning之Python篇(二)
  11. iOS 开发者必不可少的 75 个工具
  12. 集合(collection)
  13. STL_set/vector/deque
  14. 我的docker随笔3:实现加速器,加快拉取镜像速度
  15. LeetCode 67. Add Binary
  16. 新兴IT企业特斯拉(八)——自动辅助驾驶
  17. BZOJ1862: [Zjoi2006]GameZ游戏排名系统
  18. 量子力学 计算机应用,量子力学在身边:量子力学在现实世界的十大应用.doc
  19. matlab衰减曲线法整定步骤,Matlab仿真PID控制——衰减曲线法整定参数
  20. pyqt5报错——ERROR: pip‘s dependency resolver does not currently take into account all the packages that

热门文章

  1. Android Layout inflate过程分析(1)
  2. 初学者必看的JavaScript 七大点!
  3. python模拟计算器程序代码_python作业:模拟计算器
  4. GSM/GPRS模组硬件电源设计指南
  5. 4G EPS 中的小区搜索
  6. 计算机二级python易错选择题汇总
  7. BLC(Black Level Correction)——黑电平校正
  8. uniapp密码输入框
  9. 庄表伟:License之外,社区的规则与潜规则 | DEV. Together 2021 中国开发者生态峰会...
  10. 访问请转到 http://hi.baidu.com/yuyu8848