设为首页收藏本站

EPS数据狗论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1461|回复: 0

Python数据分析中的数据清洗技巧

[复制链接]

13

主题

96

金钱

155

积分

入门用户

发表于 2019-9-12 14:11:04 | 显示全部楼层 |阅读模式

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

不管你从哪里获取了数据,你都需要认真仔细观察你的数据,对不合规的数据进行清理,虽然不是说一定要有这个步骤,但是这是一个好习惯,因为保不齐后面分析的时候发现之前因为没有对数据进行整理,而导致统计的数据有问题。

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

导入数据:
  1. pd.read_excel("aa.xlsx")
  2. pd.read_csv("aa.xlsx")
  3. pd.read_clipboard
复制代码


如何有效的导入数据:
1、限定导入的行,如果数据很大,初期只是为了查看数据,可以先导入一小部分:
  1. pd.read_csv("aaa.csv",nrows=1000)
  2. pd.read_excel("aa.xlsx",nrows=1000)
复制代码


2、如果你知道需要那些列,而且知道标签名,可以只导入需要的数据:
  1. pd.read_csv("aaa.csv",usecols=["A","B"])
  2. pd.read_excel("aa.xlsx",usecols=["A","B"])
复制代码


3、关于列标签,如果没有,或者需要重新设定:
  1. pd.read_excel("aa.xlsx",header=None)#不需要原来的索引,会默认分配索引:0,1,2
  2. pd.read_excel("aa.xlsx",header=1)#设置第二行为列标签
  3. pd.read_excel("aa.xlsx",header=[1,2])#多级索引
  4. pd.read_csv("aaa.csv",header=None)
  5. pd.read_csv("aaa.csv",header=1)
  6. pd.read_csv("aaa.csv",header=[1,2])
复制代码


4、设置索引列,如果你可以提供一个更有利于数据分析的索引列,否则分配默认的0,1,2:
  1. pd.read_csv("aaa.csv",index_col=1)
  2. pd.read_excel("aa.xlsx",index_col=2)
复制代码


5、设置数值类型,这一步很重要,涉及到后期数据计算,也可以后期设置:
  1. pd.read_csv("aaa.csv",converters = {'排名': str, '场次': float})
  2. data = pd.read_excel(io, sheet_name = 'converters', converters = {'排名': str, '场次': float})
复制代码



全面的查看数据:
查看前几行:
  1. data.head()
复制代码

1.jpg

查看末尾几行:
2.jpg

查看数据维度:
  1. data.shape(16281, 7)
复制代码

查看DataFrame的数据类型
  1. df.dtypes
复制代码

查看DataFrame的索引
  1. df.index
复制代码

查看DataFrame的列索引
  1. df.columns
复制代码

查看DataFrame的值
  1. df.values
复制代码

查看DataFrame的描述
  1. df.describe()
复制代码

某一列格式:
  1. df['B'].dtype
复制代码



设置索引和标签:
有时我们经常需要重新设置索引列,或者需要重新设置列标签名字:
重新设置列标签名:
  1. df.rename(columns={"A": "a", "B": "c"})
  2. df.rename(index={0: "x", 1: "y", 2: "z"})
复制代码


重新设置索引:
  1. df.set_index('month')
复制代码


重新修改行列范围:
  1. df.reindex(['http_status', 'user_agent'], axis="columns")
  2. new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', 'Chrome']
  3. df.reindex(new_index)
复制代码


取消原有索引:
  1. df.reset_index()
复制代码


处理缺失值和重复项:
判断是否有NA:df.isnull().any()

填充NA:
  1. pf.fillna(0)
复制代码


删除含有NA的行:
  1. rs=df.dropna(axis=0)
复制代码


删除含有NA的列:
  1. rs=df.dropna(axis=1)
复制代码


删除某列的重复值:
  1. a= frame.drop_duplicates(subset=['pop'],keep='last')
复制代码



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



筛选数据:
1、按索引提取单行的数值
  1. df_inner.loc[3]
复制代码

2、按索引提取区域行数值
  1. df_inner.iloc[0:5]
复制代码

3、提取4日之前的所有数据
  1. df_inner[:’2013-01-04’]
复制代码

4、使用iloc按位置区域提取数据
  1. df_inner.iloc[:3,:2] #冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始,前三行,前两列。
复制代码

5、适应iloc按位置单独提起数据
  1. df_inner.iloc[[0,2,5],[4,5]] #提取第0、2、5行,4、5列
复制代码

6、使用ix按索引标签和位置混合提取数据
  1. df_inner.ix[:’2013-01-03’,:4] #2013-01-03号之前,前四列数据
复制代码

7、使用loc提取行和列
  1. df_inner.loc(2:10,"A":"Z")
复制代码

8、判断city列里是否包含beijing和shanghai,然后将符合条件的数据提取出来
  1. df_inner[‘city’].isin([‘beijing’])
  2. df_inner.loc[df_inner[‘city’].isin([‘beijing’,’shanghai’])]
复制代码

9、提取前三个字符,并生成数据表
  1. pd.DataFrame(category.str[:3])
复制代码

10、使用“与”进行筛选
  1. df_inner.loc[(df_inner[‘age’] > 25) & (df_inner[‘city’] == ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]]
复制代码

11、使用“或”进行筛选
  1. df_inner.loc[(df_inner[‘age’] > 25) | (df_inner[‘city’] == ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘age’])
复制代码

12、使用“非”条件进行筛选
  1. df_inner.loc[(df_inner[‘city’] != ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘id’])
复制代码

13、对筛选后的数据按city列进行计数
  1. df_inner.loc[(df_inner[‘city’] != ‘beijing’), [‘id’,’city’,’age’,’category’,’gender’]].sort([‘id’]).city.count()
复制代码

14、使用query函数进行筛选
  1. df_inner.query(‘city == [“beijing”, “shanghai”]’)
复制代码

15、对筛选后的结果按prince进行求和
  1. df_inner.query(‘city == [“beijing”, “shanghai”]’).price.sum()
复制代码


数据排序
按照特定列的值排序:
  1. df_inner.sort_values(by=[‘age’])
复制代码

按照索引列排序:
  1. df_inner.sort_index()
复制代码

升序
  1. df_inner.sort_values(by=[‘age’],ascending=True)
复制代码

降序
  1. df_inner.sort_values(by=[‘age’],ascending=False)
复制代码


合并匹配:
1、merge
  1. 1.result = pd.merge(left, right, on='key')
  2. 2.result = pd.merge(left, right, on=['key1', 'key2'])
  3. 3.result = pd.merge(left, right, how='left', on=['key1', 'key2'])
  4. 4.result = pd.merge(left, right, how='right', on=['key1', 'key2'])
  5. 5.result = pd.merge(left, right, how='outer', on=['key1', 'key2'])
复制代码


2、append
  1. 1.result = df1.append(df2)
  2. 2.result = df1.append(df4)
  3. 3.result = df1.append([df2, df3])
  4. 4.result = df1.append(df4, ignore_index=True)
复制代码


3、join
left.join(right, on=key_or_keys)
  1. 1.result = left.join(right, on='key')
  2. 2.result = left.join(right, on=['key1', 'key2'])
  3. 3.result = left.join(right, on=['key1', 'key2'], how='inner')
复制代码


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


文本处理:
1. lower()函数示例
  1. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
  2. s.str.lower()
复制代码


2. upper()函数示例
  1. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
  2. s.str.upper()
复制代码


3. len()计数
  1. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveMinsu'])
  2. s.str.len()
复制代码


4. strip()去除空格
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. s.str.strip()
复制代码


5. split(pattern)切分字符串
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. s.str.split(' ')
复制代码


6. cat(sep=pattern)合并字符串
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. s.str.cat(sep=' <=> ')
  3. 执行上面示例代码,得到以下结果 -
  4. Tom <=> William Rick <=> John <=> Alber@t
复制代码


7. get_dummies()用sep拆分每个字符串,返回一个虚拟/指示dataFrame
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. s.str.get_dummies()
复制代码


8. contains()判断字符串中是否包含子串true; pat str或正则表达式
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. s.str.contains(' ')
复制代码


9. replace(a,b)将值pat替换为值b。
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. .str.replace('@','

  3. 10. repeat(value)重复每个元素指定的次数
  4. [code]s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  5. s.str.repeat(2)
复制代码


执行上面示例代码,得到以下结果
0 Tom Tom
1 William Rick William Rick
2 JohnJohn
3 Alber@tAlber@t

11. count(pattern)子串出现次数
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print ("The number of 'm's in each string:")
  3. 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
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print ("Strings that start with 'T':")
  3. print (s.str. startswith ('T'))
复制代码


执行上面示例代码,得到以下结果
Strings that start with 'T':
0 True
1 False
2 False
3 False

13. endswith(pattern)字符串结尾是否是特定子串 true
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print ("Strings that end with 't':")
  3. print (s.str.endswith('t'))
复制代码


执行上面示例代码,得到以下结果
Strings that end with 't':
0 False
1 False
2 False
3 True

14. find(pattern)查子串首索引,子串包含在[start:end];无返回-1
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print (s.str.find('e'))
复制代码

执行上面示例代码,得到以下结果
0 -1
1 -1
2 -1
3 3
注意:-1表示元素中没有这样的模式可用。

15. findall(pattern)查找所有符合正则表达式的字符,以数组形式返回
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print (s.str.findall('e'))
复制代码


执行上面示例代码,得到以下结果 -
0 []
1 []
2 []
3 [e]

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

16. swapcase()变换字母大小写,大变小,小变大
  1. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
  2. s.str.swapcase()
复制代码

执行上面示例代码,得到以下结果
1.tOM
2.wILLIAM rICK
3.jOHN
4.aLBER

17. islower()检查是否都是大写
  1. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
  2. s.str.islower()
复制代码


18. isupper()检查是否都是大写
  1. s = pd.Series(['TOM', 'William Rick', 'John', 'Alber@t'])
  2. s.str.isupper()
复制代码


19. isnumeric()检查是否都是数字
  1. s = pd.Series(['Tom', '1199','William Rick', 'John', 'Alber@t'])
  2. s.str.isnumeric()
复制代码
) [/code]

10. repeat(value)重复每个元素指定的次数
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print ("The number of 'm's in each string:")
  3. print (s.str.count('m'))
复制代码


执行上面示例代码,得到以下结果
0 Tom Tom
1 William Rick William Rick
2 JohnJohn
3 Alber@tAlber@t

11. count(pattern)子串出现次数
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print ("Strings that start with 'T':")
  3. print (s.str. startswith ('T'))
复制代码


执行上面示例代码,得到以下结果 -
The number of 'm's in each string:
0 1
1 1
2 0
3 0

12. startswith(pattern)字符串开头是否匹配子串True
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print ("Strings that end with 't':")
  3. print (s.str.endswith('t'))
复制代码


执行上面示例代码,得到以下结果
Strings that start with 'T':
0 True
1 False
2 False
3 False

13. endswith(pattern)字符串结尾是否是特定子串 true
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print (s.str.find('e'))
复制代码


执行上面示例代码,得到以下结果
Strings that end with 't':
0 False
1 False
2 False
3 True

14. find(pattern)查子串首索引,子串包含在[start:end];无返回-1
  1. s = pd.Series(['Tom ', ' William Rick', 'John', 'Alber@t'])
  2. print (s.str.findall('e'))
复制代码

执行上面示例代码,得到以下结果
0 -1
1 -1
2 -1
3 3
注意:-1表示元素中没有这样的模式可用。

15. findall(pattern)查找所有符合正则表达式的字符,以数组形式返回
  1. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
  2. s.str.swapcase()
复制代码


执行上面示例代码,得到以下结果 -
0 []
1 []
2 []
3 [e]

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

16. swapcase()变换字母大小写,大变小,小变大
  1. s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t'])
  2. s.str.islower()
复制代码

执行上面示例代码,得到以下结果
1.tOM
2.wILLIAM rICK
3.jOHN
4.aLBER

17. islower()检查是否都是大写
  1. s = pd.Series(['TOM', 'William Rick', 'John', 'Alber@t'])
  2. s.str.isupper()
复制代码


18. isupper()检查是否都是大写
  1. s = pd.Series(['Tom', '1199','William Rick', 'John', 'Alber@t'])
  2. s.str.isnumeric()
复制代码


19. isnumeric()检查是否都是数字
[        DISCUZ_CODE_64        ]
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

客服中心
关闭
在线时间:
周一~周五
8:30-17:30
QQ群:
653541906
联系电话:
010-85786021-8017
在线咨询
客服中心

意见反馈|网站地图|手机版|小黑屋|EPS数据狗论坛 ( 京ICP备09019565号-3 )   

Powered by BFIT! X3.4

© 2008-2028 BFIT Inc.

快速回复 返回顶部 返回列表