百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

技术分享:Python数据分析学习(python数据分析教程视频)

toyiye 2024-08-09 10:32 8 浏览 0 评论

所有做数据分析的前提就是:你得有数据,而且已经经过清洗,整理成需要的格式。作者:哗啦圈的梦


不管你从哪里获取了数据,你都需要认真仔细观察你的数据,对不合规的数据进行清理,虽然不是说一定要有这个步骤,但是这是一个好习惯,因为保不齐后面分析的时候发现之前因为没有对数据进行整理,而导致统计的数据有问题,今天就把平时用的数据清洗的技巧进行一个梳理,里面可能很多你都懂,那就当温习了吧!

文章大纲:

  1. 如何更有效的导入你的数据
  2. 全面的观察数据
  3. 设置索引
  4. 设置标签
  5. 处理缺失值
  6. 删除重复项
  7. 数据类型转换
  8. 筛选数据
  9. 数据排序
  10. 处理文本
  11. 合并&匹配

导入数据:

pd.read_excel("aa.xlsx") 
pd.read_csv("aa.xlsx") 
pd.read_clipboard 

如何有效的导入数据:

1、限定导入的行,如果数据很大,初期只是为了查看数据,可以先导入一小部分:

pd.read_csv("aaa.csv",nrows=1000) 
pd.read_excel("aa.xlsx",nrows=1000) 

2、如果你知道需要那些列,而且知道标签名,可以只导入需要的数据:

pd.read_csv("aaa.csv",usecols=["A","B"]) 
pd.read_excel("aa.xlsx",usecols=["A","B"]) 

3、关于列标签,如果没有,或者需要重新设定:

pd.read_excel("aa.xlsx",header=None)#不需要原来的索引,会默认分配索引:0,1,2 
pd.read_excel("aa.xlsx",header=1)#设置第二行为列标签 
pd.read_excel("aa.xlsx",header=[1,2])#多级索引 
pd.read_csv("aaa.csv",header=None) 
pd.read_csv("aaa.csv",header=1) 
pd.read_csv("aaa.csv",header=[1,2]) 

4、设置索引列,如果你可以提供一个更有利于数据分析的索引列,否则分配默认的0,1,2:

pd.read_csv("aaa.csv",index_col=1) 
pd.read_excel("aa.xlsx",index_col=2) 

5、设置数值类型,这一步很重要,涉及到后期数据计算,也可以后期设置:

pd.read_csv("aaa.csv",converters = {'排名': str, '场次': float}) 
data = pd.read_excel(io, sheet_name = 'converters', converters = {'排名': str, '场次': float}) 

全面的查看数据:

查看前几行:

data.head() 



查看末尾几行:

查看数据维度:

data.shape(16281, 7) 

查看DataFrame的数据类型

df.dtypes 

查看DataFrame的索引

df.index 

查看DataFrame的列索引

df.columns 

查看DataFrame的值

df.values 

查看DataFrame的描述

df.describe() 

某一列格式:

df['B'].dtype 

设置索引和标签:

有时我们经常需要重新设置索引列,或者需要重新设置列标签名字:

重新设置列标签名:

df.rename(columns={"A": "a", "B": "c"}) 
df.rename(index={0: "x", 1: "y", 2: "z"}) 

重新设置索引:

df.set_index('month') 

重新修改行列范围:

df.reindex(['http_status', 'user_agent'], axis="columns") 
new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', 'Chrome'] 
df.reindex(new_index) 

取消原有索引:

df.reset_index() 

处理缺失值和重复项:

判断是否有NA:df.isnull().any()

填充NA:

pf.fillna(0) 

删除含有NA的行:

rs=df.dropna(axis=0) 

删除含有NA的列:

rs=df.dropna(axis=1) 

删除某列的重复值:

a= frame.drop_duplicates(subset=['pop'],keep='last') 

数据类型转换:

df.dtypes:查看数值类型

  1. astype()强制转化数据类型
  2. 通过创建自定义的函数进行数据转化
  3. pandas提供的to_nueric()以及to_datetime()
df["Active"].astype("bool") 
df['2016'].astype('float') 
df["2016"].apply(lambda x: x.replace(",","").replace("$","")).astype("float64") 
df["Percent Growth"].apply(lambda x: x.replace("%","")).astype("float")/100 
pd.to_numeric(df["Jan Units"],errors='coerce').fillna(0) 
pd.to_datetime(df[['Month', 'Day', 'Year']]) 

筛选数据:

1、按索引提取单行的数值

df_inner.loc[3] 

2、按索引提取区域行数值

df_inner.iloc[0:5] 

3、提取4日之前的所有数据

df_inner[:’2013-01-04’] 

4、使用iloc按位置区域提取数据

df_inner.iloc[:3,:2] #冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始,前三行,前两列。 

5、适应iloc按位置单独提起数据

df_inner.iloc[[0,2,5],[4,5]] #提取第0、2、5行,4、5列 

6、使用ix按索引标签和位置混合提取数据

df_inner.ix[:’2013-01-03’,:4] #2013-01-03号之前,前四列数据 

7、使用loc提取行和列

df_inner.loc(2:10,"A":"Z") 

8、判断city列里是否包含beijing和shanghai,然后将符合条件的数据提取出来

df_inner[‘city’].isin([‘beijing’]) 
df_inner.loc[df_inner[‘city’].isin([‘beijing’,’shanghai’])] 

9、提取前三个字符,并生成数据表

pd.DataFrame(category.str[:3]) 

10、使用“与”进行筛选

df_inner.loc[(df_inner[‘age’] > 25) & (df_inner[‘city’] == ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]] 

11、使用“或”进行筛选

df_inner.loc[(df_inner[‘age’] > 25) | (df_inner[‘city’] == ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘age’]) 

12、使用“非”条件进行筛选

df_inner.loc[(df_inner[‘city’] != ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘id’]) 

13、对筛选后的数据按city列进行计数

df_inner.loc[(df_inner[‘city’] != ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘id’]).city.count() 

14、使用query函数进行筛选

df_inner.query(‘city == [“beijing”, “shanghai”]’) 

15、对筛选后的结果按prince进行求和

df_inner.query(‘city == [“beijing”, “shanghai”]’).price.sum() 

数据排序

按照特定列的值排序:

df_inner.sort_values(by=[‘age’]) 

按照索引列排序:

df_inner.sort_index() 

升序

df_inner.sort_values(by=[‘age’],ascending=True) 

降序

df_inner.sort_values(by=[‘age’],ascending=False) 

合并匹配:

merge

1.result = pd.merge(left, right, on='key') 
2.result = pd.merge(left, right, on=['key1', 'key2']) 
3.result = pd.merge(left, right, how='left', on=['key1', 'key2']) 
4.result = pd.merge(left, right, how='right', on=['key1', 'key2']) 
5.result = pd.merge(left, right, how='outer', on=['key1', 'key2']) 

2、append

1.result = df1.append(df2) 
2.result = df1.append(df4) 
3.result = df1.append([df2, df3]) 
4.result = df1.append(df4, ignore_index=True) 

4、join

left.join(right, on=key_or_keys)

1.result = left.join(right, on='key') 
2.result = left.join(right, on=['key1', 'key2']) 
3.result = left.join(right, on=['key1', 'key2'], how='inner') 

5、concat

1.result = pd.concat([df1, df4], axis=1) 
2.result = pd.concat([df1, df4], axis=1, join='inner') 
3.result = pd.concat([df1, df4], axis=1, join_axes=[df1.index]) 
4.result = pd.concat([df1, df4], ignore_index=True) 

文本处理:

1. lower()函数示例

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu']) 
s.str.lower() 

2. upper()函数示例

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu']) 
s.str.upper() 

3. len()计数

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu']) 
s.str.len() 

4. strip()去除空格

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
s.str.strip() 

5. split(pattern)切分字符串

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
s.str.split(' ') 

6. cat(sep=pattern)合并字符串

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
s.str.cat(sep=' <=> ') 
执行上面示例代码,得到以下结果 - 
Tom <=> William Rick <=> John <=> Alber@t 

7. get_dummies()用sep拆分每个字符串,返回一个虚拟/指示dataFrame

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
s.str.get_dummies() 

8. contains()判断字符串中是否包含子串true; pat str或正则表达式

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
s.str.contains(' ') 

9. replace(a,b)将值pat替换为值b。

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
.str.replace('@','$') 

10. repeat(value)重复每个元素指定的次数

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
s.str.repeat(2) 

执行上面示例代码,得到以下结果 -

  • 0 Tom Tom
  • 1 William Rick William Rick
  • 2 JohnJohn
  • 3 Alber@tAlber@t

11. count(pattern)子串出现次数

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
print ("The number of 'm's in each string:") 
print (s.str.count('m')) 

执行上面示例代码,得到以下结果 -

The number of 'm's in each string:

  • 0 1
  • 1 1
  • 2 0
  • 3 0

12. startswith(pattern)字符串开头是否匹配子串True

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
print ("Strings that start with 'T':") 
print (s.str. startswith ('T')) 

执行上面示例代码,得到以下结果 -

Strings that start with 'T':

  • 0 True
  • 1 False
  • 2 False
  • 3 False


13. endswith(pattern)字符串结尾是否是特定子串 true

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
print ("Strings that end with 't':") 
print (s.str.endswith('t')) 

执行上面示例代码,得到以下结果 -

Strings that end with 't':

  • 0 False
  • 1 False
  • 2 False
  • 3 True

14. find(pattern)查子串首索引,子串包含在[start:end];无返回-1

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
print (s.str.find('e')) 

执行上面示例代码,得到以下结果 -

  • 0 -1
  • 1 -1
  • 2 -1
  • 3 3

注意:-1表示元素中没有这样的模式可用。

15. findall(pattern)查找所有符合正则表达式的字符,以数组形式返回

s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t']) 
print (s.str.findall('e')) 

执行上面示例代码,得到以下结果 -

  • 0 []
  • 1 []
  • 2 []
  • 3 [e]

空列表([])表示元素中没有这样的模式可用。

16. swapcase()变换字母大小写,大变小,小变大

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t']) 
s.str.swapcase() 

执行上面示例代码,得到以下结果 -

  1. tOM
  2. wILLIAM rICK
  3. jOHN
  4. aLBER

17. islower()检查是否都是大写

s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t']) 
s.str.islower() 

18. isupper()检查是否都是大写

s = pd.Series(['TOM', 'William Rick', 'John', 'Alber@t']) 
s.str.isupper() 

19. isnumeric()检查是否都是数字

s = pd.Series(['Tom', '1199','William Rick', 'John', 'Alber@t']) 
s.str.isnumeric() 


相关推荐

Python教父推荐:《Python基础教程》(第3版)

《Python基础教程第3版》包括Python程序设计的方方面面:首先,从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句;然后循序渐进地...

今日精选5篇教程:用Python3带你从小白入门机器学习实战教程手册

正文1:教程标题:英伟达SuperSloMoGithub项目开放作者:英伟达教程摘要:今年6月份,英伟达发布了一份生成高质量慢动作视频的论文——《SuperSloMo:HighQual...

电子书 | 笨办法学 Python 3(笨办法学python3pdf)

本周更新了5本IT电子书资源,同时站内已经有12本Python入门方面的相关电子书,可供新手选择。1、笨办法学Python3本书是一本Python入门书,适合对计算机了解不多,没有...

Python2 已终结,入手Python 3,你需要这30个技巧

选自medium作者:Erik-JanvanBaaren机器之心编译参与:王子嘉、一鸣Python2在今年和我们说拜拜了,Python3有哪些有趣而又实用的技巧呢?这篇教程有30个你会喜欢...

Python 3 系列教程(python3.9基础教程)

Python的3.0版本,常被称为Python3000,或简称Py3k。相对于Python的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python3.0在设计的时候没有考...

Python第三课3. Python 的非正式介绍

3.Python的非正式介绍?在下面的例子中,通过提示符(>>>与...)的出现与否来区分输入和输出:如果你想复现这些例子,当提示符出现后,你必须在提示符后键入例子中的每...

如何使用 Python 构建一个“谷歌搜索”系统?| 内附代码

来源|hackernoon编译|武明利,责编|Carol出品|AI科技大本营(ID:rgznai100)在这篇文章中,我将向您展示如何使用Python构建自己的答案查找系统。基本上,这...

Python 模拟微博登陆,亲测有效!(如何用python爬微博)

今天想做一个微博爬个人页面的工具,满足一些不可告人的秘密。那么首先就要做那件必做之事!模拟登陆……代码是参考了:https://www.douban.com/note/201767245/,我对代码进...

Python 驱动的 AI 艺术批量创作: 免费的Bing 绘图代码解析

这篇文章将深入分析一段Python代码,该代码利用Bing的AI绘图功能,即bing的images/create,根据用户提供的文本提示生成图像。我们将详细探讨其工作原理、代码结构、...

Python爬虫Scrapy库的使用入门?(python scrapy爬虫)

Scrapy是一个开源的并且支持高度可扩展的Python爬虫框架,主要被用来实现从网站提取数据。出现之初就是为网页抓取而设计,但是现在它也可以被用于从APIs中抓取数据或通用的Web抓取任务。Sc...

Python3 标准库概览(python标准库有什么)

操作系统接口os模块提供了不少与操作系统相关联的函数。>>>importos>>>os.getcwd()#返回当前的工作目录'C:\\Python34...

零基础入门学习Python(三):变量和字符串

分享兴趣,传播快乐,增长见闻,留下美好!亲爱的您,这里是LearningYard新学苑。今天小编为大家带来的是...

Python读写docx文件(python读写word)

Python读写docx文件Python读写word文档有现成的库可以处理pipinstallpython-docx安装一下。https://python-docx.readthedocs.io/...

如何利用Xpath抓取京东网商品信息

前几小编分别利用Python正则表达式和BeautifulSoup爬取了京东网商品信息,今天小编利用Xpath来为大家演示一下如何实现京东商品信息的精准匹配~~HTML文件其实就是由一组尖括号构成的标...

如何利用Xpath选择器抓取京东网商品信息

前几小编分别利用Python正则表达式和BeautifulSoup爬取了京东网商品信息,今天小编利用Xpath来为大家演示一下如何实现京东商品信息的精准匹配~~HTML文件其实就是由一组尖括号构成的标...

取消回复欢迎 发表评论:

请填写验证码