-
python爬虫之对pandas进行数据预处理的实例讲解
本站最新发布 Python从入门到精通|Python基础教程
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
试听地址 https://www.xin3721.com/eschool/pythonxin3721/
引入包和加载数据
|
1
2
3
4
5
|
import pandas as pdimport numpy as nptrain_df =pd.read_csv('../datas/train.csv') # train settest_df = pd.read_csv('../datas/test.csv') # test setcombine = [train_df, test_df] |
清洗数据
查看数据维度以及类型
缺失值处理
查看object数据统计信息
数值属性离散化
计算特征与target属性之间关系
查看数据维度以及类型
|
1
2
3
4
5
6
|
#查看前五条数据print train_df.head(5) #查看每列数据类型以及nan情况print train_df.info() # 获得所有object属性print train_data.describe(include=['O']).columns |
查看object数据统计信息
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
#查看连续数值属性基本统计情况print train_df.describe() #查看object属性数据统计情况print train_df.describe(include=['O']) # 统计Title单列各个元素对应的个数print train_df['Title'].value_counts() # 属性列删除train_df = train_df.drop(['Name', 'PassengerId'], axis=1) 缺失值处理# 直接丢弃缺失数据列的行print df4.dropna(axis=0,subset=['col1']) # 丢弃nan的行,subset指定查看哪几列 print df4.dropna(axis=1) # 丢弃nan的列# 采用其他值填充dataset['Cabin'] = dataset['Cabin'].fillna('U') dataset['Title'] = dataset['Title'].fillna(0) # 采用出现最频繁的值填充freq_port = train_df.Embarked.dropna().mode()[0]dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)# 采用中位数或者平均数填充test_df['Fare'].fillna(test_df['Fare'].dropna().median(), inplace=True)test_df['Fare'].fillna(test_df['Fare'].dropna().mean(), inplace=True)数值属性离散化,object属性数值化# 创造一个新列,FareBand,将连续属性Fare切分成四份train_df['FareBand'] = pd.qcut(train_df['Fare'], 4)# 查看切分后的属性与target属性Survive的关系train_df[['FareBand', 'Survived']].groupby(['FareBand'], as_index=False).mean().sort_values(by='FareBand', ascending=True)# 建立object属性映射字典 title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Royalty":5, "Officer": 6}dataset['Title'] = dataset['Title'].map(title_mapping)计算特征与target属性之间关系object与连续target属性之间,可以groupby均值object与离散target属性之间,先将target数值化,然后groupby均值,或者分别条形统计图连续属性需要先切割然后再进行groupby计算,或者pearson相关系数print train_df[['AgeBand', 'Survived']].groupby(['AgeBand'], as_index=False).mean().sort_values(by='AgeBand', ascending=True)总结pandas基本操作”' 创建df对象 ””' s1 = pd.Series([1,2,3,np.nan,4,5]) s2 = pd.Series([np.nan,1,2,3,4,5]) print s1 dates = pd.date_range(“20130101”,periods=6) print dates df = pd.DataFrame(np.random.rand(6,4),index=dates,columns=list(“ABCD”)) # print df df2 = pd.DataFrame({“A”:1, ‘B':pd.Timestamp(‘20130102'), ‘C':pd.Series(1,index=list(range(4)),dtype='float32'), ‘D':np.array([3]*4,dtype=np.int32), ‘E':pd.Categorical([‘test','train','test','train']), ‘F':'foo' }) # print df2.dtypesdf3 = pd.DataFrame({'col1':s1, 'col2':s2})print df3'''2.查看df数据'''print df3.head(2) #查看头几条print df3.tail(3) #查看尾几条print df.index #查看索引print df.info() #查看非non数据条数print type(df.values) #返回二元数组# print df3.valuesprint df.describe() #对每列数据进行初步的统计print df3print df3.sort_values(by=['col1'],axis=0,ascending=True) #按照哪几列排序'''3.选择数据'''ser_1 = df3['col1']print type(ser_1) #pandas.core.series.Seriesprint df3[0:2] #前三行print df3.loc[df3.index[0]] #通过index来访问print df3.loc[df3.index[0],['col2']] #通过行index,和列名来唯一确定一个位置print df3.iloc[1] #通过位置来访问print df3.iloc[[1,2],1:2] #通过位置来访问print "==="print df3.loc[:,['col1','col2']].as_matrix() # 返回nunpy二元数组print type(df3.loc[:,['col1','col2']].as_matrix())'''4.布尔索引,过滤数据'''print df3[df3.col1 >2]df4 = df3.copy()df4['col3']=pd.Series(['one','two','two','three','one','two'])print df4print df4[df4['col3'].isin(['one','two'])]df4.loc[:,'col3']="five"print df4'''5.缺失值处理,pandas将缺失值用nan代替'''print pd.isnull(df4)print df4.dropna(axis=0,subset=['col1']) # 丢弃nan的行,subset指定查看哪几列print df4.dropna(axis=1) # 丢弃nan的列 |
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能













