资讯专栏INFORMATION COLUMN

对pandas进行数据预处理的实例讲解

psychola / 1217人阅读

摘要:引入包和加载数据清洗数据查看数据维度以及类型缺失值处理查看数据统计信息数值属性离散化计算特征与属性之间关系查看数据维度以及类型查看前五条数据查看每列数据类型以及情况获得所有属性查看数据统计信息查看连续数值属性基本统计情况查看属性数据统计情况

引入包和加载数据

1
2
3
4
5
import pandas as pd
import numpy as np
train_df =pd.read_csv("../datas/train.csv") # train set
test_df = pd.read_csv("../datas/test.csv") # test set
combine = [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.dtypes

df3 = 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.values

print df.describe() #对每列数据进行初步的统计
print df3
print df3.sort_values(by=["col1"],axis=0,ascending=True) #按照哪几列排序
"""
3.选择数据
"""
ser_1 = df3["col1"]
print type(ser_1) #pandas.core.series.Series
print 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 df4
print 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的列

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43330.html

相关文章

  • 我是如何入门机器学习

    摘要:在这里我分享下我个人入门机器学习的经历,希望能对大家能有所帮助。相关学习链接,,入门后的体验在入门了机器学习之后,在实际工作中,绝大多数的情况下你并不需要去创造一个新的算法。 机器学习在很多眼里就是香饽饽,因为机器学习相关的岗位在当前市场待遇不错,但同时机器学习在很多人面前又是一座大山,因为发现它太难学了。在这里我分享下我个人入门机器学习的经历,希望能对大家能有所帮助。 PS:这篇文章...

    ShowerSun 评论0 收藏0
  • Python Pandas中loc和iloc函数基本用法讲解

      Python Pandas的主要左右是解决大量的数据,快速的对数据去进行批量的处理,大大提高工作的效率。那么,里面的loc和iloc函数,具体是怎么进行使用呢?怎么知道每个函数的基本用法呢?下面小编就给大家详细的解答下。  1 loc和iloc的含义  loc表示location的意思;iloc中的loc意思相同,前面的i表示integer,所以它只接受整数作为参数。  2用法  import...

    89542767 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<