datawhale1

有一段代码错误,但是不知道哪里错了。。。

开始之前,导入numpy、pandas包和数据
In [85]:

#加载所需的库
import numpy as np
import pandas as pd
In [86]:

#加载数据train.csv
df = pd.read_csv(‘train.csv’)
df.head(3)

Out[86]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
2 第二章:数据清洗及特征处理
我们拿到的数据通常是不干净的,所谓的不干净,就是数据中有缺失值,有一些异常点等,需要经过一定的处理才能继续做后面的分析或建模,所以拿到数据的第一步是进行数据清洗,本章我们将学习缺失值、重复值、字符串和数据转换等操作,将数据清洗成可以分析或建模的亚子。
2.1 缺失值观察与处理
我们拿到的数据经常会有很多缺失值,比如我们可以看到Cabin列存在NaN,那其他列还有没有缺失值,这些缺失值要怎么处理呢
2.1.1 任务一:缺失值观察
(1) 请查看每个特征缺失值个数
(2) 请查看Age, Cabin, Embarked列的数据 以上方式都有多种方式,所以大家多多益善
In [87]:

#写入代码
df.info()


<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):

Column Non-Null Count Dtype


0 PassengerId 891 non-null int64
1 Survived 891 non-null int64
2 Pclass 891 non-null int64
3 Name 891 non-null object
4 Sex 891 non-null object
5 Age 714 non-null float64
6 SibSp 891 non-null int64
7 Parch 891 non-null int64
8 Ticket 891 non-null object
9 Fare 891 non-null float64
10 Cabin 204 non-null object
11 Embarked 889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KB
In [88]:

#写入代码
df.isnull().sum()


Out[88]:
PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 177
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 2
dtype: int64
In [89]:

#写入代码
xx = df[[‘Age’, ‘Cabin’, ‘Embarked’]]
xx.head(3)

Out[89]:
Age Cabin Embarked
0 22.0 NaN S
1 38.0 C85 C
2 26.0 NaN S
2.1.2 任务二:对缺失值进行处理
(1)处理缺失值一般有几种思路
(2) 请尝试对Age列的数据的缺失值进行处理
(3) 请尝试使用不同的方法直接对整张表的缺失值进行处理
In [90]:

#处理缺失值的一般思路:
#提醒:可使用的函数有—>dropna函数与fillna函数
df[df[‘Age’].isnull()]=0
df.head(3)


Out[90]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
In [91]:

#写入代码
df[df[‘Age’]==None]=0
df.head()


Out[91]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S
In [92]:

#写入代码
df[df[‘Age’] == np.nan] = 0
df.head()


Out[92]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S
In [93]:

#写入代码
df.dropna().head(3)


Out[93]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
5 0 0 0 0 0 0.0 0 0 0 0.0000 0 0
【思考1】dropna和fillna有哪些参数,分别如何使用呢?
【思考2】检索空缺值用np.nan要比用None好,这是为什么?
In [94]:

#思考回答
df.fillna(0).head(3)


Out[94]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 0 S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 0 S
【参考】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html
【参考】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html
2.2 重复值观察与处理
由于这样那样的原因,数据中会不会存在重复值呢,如果存在要怎样处理呢
2.2.1 任务一:请查看数据中的重复值
In [99]:

#重复值有哪些处理方式:
df[df.duplicated()]


Out[99]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
17 0 0 0 0 0 0.0 0 0 0 0.0 0 0
19 0 0 0 0 0 0.0 0 0 0 0.0 0 0
26 0 0 0 0 0 0.0 0 0 0 0.0 0 0
28 0 0 0 0 0 0.0 0 0 0 0.0 0 0
29 0 0 0 0 0 0.0 0 0 0 0.0 0 0
… … … … … … … … … … … … …
859 0 0 0 0 0 0.0 0 0 0 0.0 0 0
863 0 0 0 0 0 0.0 0 0 0 0.0 0 0
868 0 0 0 0 0 0.0 0 0 0 0.0 0 0
878 0 0 0 0 0 0.0 0 0 0 0.0 0 0
888 0 0 0 0 0 0.0 0 0 0 0.0 0 0
176 rows × 12 columns
In [100]:

#写入代码



2.2.2 任务二:对重复值进行处理
(1)重复值有哪些处理方式呢?
(2)处理我们数据的重复值
方法多多益善
In [101]:

#写入代码

df.drop_duplicates().head()

Out[101]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S
2.2.3 任务三:将前面清洗的数据保存为csv格式
In [102]:

#写入代码
df.to_csv(‘test_clear.csv’)


2.3 特征观察与处理
我们对特征进行一下观察,可以把特征大概分为两大类:
数值型特征:Survived ,Pclass, Age ,SibSp, Parch, Fare,其中Survived, Pclass为离散型数值特征,Age,SibSp, Parch, Fare为连续型数值特征
文本型特征:Name, Sex, Cabin,Embarked, Ticket,其中Sex, Cabin, Embarked, Ticket为类别型文本特征,数值型特征一般可以直接用于模型的训练,但有时候为了模型的稳定性及鲁棒性会对连续变量进行离散化。文本型特征往往需要转换成数值型特征才能用于建模分析。
2.3.1 任务一:对年龄进行分箱(离散化)处理
(1) 分箱操作是什么?
(2) 将连续变量Age平均分箱成5个年龄段,并分别用类别变量12345表示
(3) 将连续变量Age划分为[0,5) [5,15) [15,30) [30,50) [50,80)五个年龄段,并分别用类别变量12345表示
(4) 将连续变量Age按10% 30% 50 70% 90%五个年龄段,并用分类变量12345表示
(5) 将上面的获得的数据分别进行保存,保存为csv格式
In [103]:

#分箱操作是什么:



In [104]:

#写入代码

df[‘Ageband’] = pd.cut(df[‘Age’], 5, labels = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’])
df.head()
Out[104]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Ageband
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S b
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C c
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S b
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S c
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S c
In [105]:

#写入代码
df.to_csv(‘test_ave.csv’)

In [106]:

df[‘Ageband’] = pd.cut(df[‘Age’], [0, 5, 15, 30, 50, 80], labels = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’])
df.head()

Out[106]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Ageband
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S c
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C d
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S c
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S d
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S d
In [107]:

df.to_csv(‘test_cut.csv’)
In [108]:

#写入代码
df[‘AgeBand’] = pd.qcut(df[‘Age’], [0, 0.1, 0.3, 0.5, 0.7, 0.9], labels = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’])
df.head()

ValueError Traceback (most recent call last)
in
1 #写入代码
----> 2 df[‘AgeBand’] = pd.qcut(df[‘Age’], [0, 0.1, 0.3, 0.5, 0.7, 0.9], labels = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’])
3 df.head()
4

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/tile.py in qcut(x, q, labels, retbins, precision, duplicates)
346 include_lowest=True,
347 dtype=dtype,
–> 348 duplicates=duplicates,
349 )
350

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/reshape/tile.py in _bins_to_cuts(x, bins, right, labels, precision, include_lowest, dtype, duplicates)
379 if duplicates == “raise”:
380 raise ValueError(
–> 381 f"Bin edges must be unique: {repr(bins)}.\n"
382 f"You can drop duplicate edges by setting the ‘duplicates’ kwarg"
383 )

ValueError: Bin edges must be unique: array([ 0. , 0. , 16. , 24. , 32.5, 47. ]).
You can drop duplicate edges by setting the ‘duplicates’ kwarg

In [ ]:


【参考】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html
【参考】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.qcut.html
2.3.2 任务二:对文本变量进行转换
(1) 查看文本变量名及种类
(2) 将文本变量Sex, Cabin ,Embarked用数值变量12345表示
(3) 将文本变量Sex, Cabin, Embarked用one-hot编码表示
In [109]:

#写入代码
df[‘Sex’].value_counts()


Out[109]:
male 453
female 261
0 177
Name: Sex, dtype: int64
In [110]:

#写入代码
df[‘Sex’].unique()


Out[110]:
array([‘male’, ‘female’, 0], dtype=object)
In [111]:

#写入代码
df[‘Sex’].nunique()


Out[111]:
3
In [112]:

df[‘Sex_num’] = df[‘Sex’].replace([‘male’,‘female’],[1,2])
df.head()
Out[112]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Ageband Sex_num
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S c 1
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C d 2
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S c 2
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S d 2
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S d 1
In [ ]:


In [ ]:


In [ ]:


2.3.3 任务三:从纯文本Name特征里提取出Titles的特征(所谓的Titles就是Mr,Miss,Mrs等)
In [113]:

#写入代码

df[‘Title’] = df.Name.str.extract(’([A-Za-z]+).’, expand=False)
df.head()

Out[113]:
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked Ageband Sex_num Title
0 1 0 3 Braund, Mr. Owen Harris male 22.0 1 0 A/5 21171 7.2500 NaN S c 1 Mr
1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th… female 38.0 1 0 PC 17599 71.2833 C85 C d 2 Mrs
2 3 1 3 Heikkinen, Miss. Laina female 26.0 0 0 STON/O2. 3101282 7.9250 NaN S c 2 Miss
3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female 35.0 1 0 113803 53.1000 C123 S d 2 Mrs
4 5 0 3 Allen, Mr. William Henry male 35.0 0 0 373450 8.0500 NaN S d 1 Mr
In [114]:

#保存最终你完成的已经清理好的数据
df.to_csv(‘test_fin.csv’)
In [ ]:


版权声明:本文为sima0313原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。