5个提高效率的Pandas实用技巧

来源:互联网 发布:des算法c 编辑:程序博客网 时间:2024/06/11 05:20

Python 正迅速成为数据科学家们更为钟爱的编程语言。形成该现状的理由非常充分:Python 提供了一种覆盖范围更为广阔的编程语言生态系统,以及具有一定计算深度且性能良好的科学计算库。如果您是 Python 初学者,建议首先看下Python 学习路线。在 Python 自带的科学计算库中,Pandas 模块是最适于数据科学相关操作的工具。它与 Scikit-learn 两个模块几乎提供了数据科学家所需的全部工具。本文着重学习Pandas中数据处理的 5种方法。这些将有助于您提高工作效率。

在本文开始前,推荐读者首先了解一些数据挖掘的相关代码。为使本文更易于理解,我们事先选定了一个数据集以示范相关操作和处理方法。

数据集来源:本文采用的是贷款预测问题的数据集。请下载该数据集并开始本文内容。

让我们开始吧

首先导入相关模块并加载数据集到 Python 环境中:

Python

1

2

3

import pandas as pd

import numpy as np

data = pd.read_csv("train.csv", index_col="Loan_ID")

#1 – 布尔索引

如果需要以其它列数据值为条件过滤某一列的数据,您会怎么处理?例如建立一个列表,列表中全部为未能毕业但曾获得贷款的女性。这里可以使用布尔索引,代码如下:

Python

1

2

data.loc[(data["Gender"]=="Female") & (data["Education"]=="Not Graduate") & (data["Loan_Status"]=="Y"),

["Gender","Education","Loan_Status"]]

#2 – Apply 函数

Apply 函数是处理数据和建立新变量的常用函数之一。在向数据框的每一行或每一列传递指定函数后,Apply 函数会返回相应的值。这个由 Apply 传入的函数可以是系统默认的或者用户自定义的。例如,在下面的例子中它可以用于查找每一行和每一列中的缺失值。

Python

1

2

3

4

5

6

7

8

9

10

11

#Create a new function:

def num_missing(x):

  return sum(x.isnull())

 

#Applying per column:

print "Missing values per column:"

print data.apply(num_missing, axis=0) #axis=0 defines that function is to be applied on each column

 

#Applying per row:

print "nMissing values per row:"

print data.apply(num_missing, axis=1).head() #axis=1 defines that function is to be applied on each row

这样我们就得到了所需的结果。

注:由于输出结果包含多行数据,第二个输出函数使用了 head() 函数以限定输出数据长度。在不限定输入参数时 head() 函数默认输出 5 行数据。

#3 – 填补缺失值

fillna() 函数可一次性完成填补功能。它可以利用所在列的均值/众数/中位数来替换该列的缺失数据。下面利用“Gender”、“Married”、和“Self_Employed”列中各自的众数值填补对应列的缺失数据。

Python

1

2

3

#First we import a function to determine the mode

from scipy.stats import mode

mode(data['Gender'])

输出结果为:ModeResult(mode=array([‘Male’], dtype=object), count=array([489]))

输出结果返回了众数值和对应次数。需要记住的是由于可能存在多个高频出现的重复数据,因此众数可以是一个数组。通常默认使用第一个众数值:

Python

1

mode(data['Gender']).mode[0]

 

现在可以进行缺失数据值填补并利用#2方法进行检查。

Python

1

2

3

4

5

6

7

#Impute the values:

data['Gender'].fillna(mode(data['Gender']).mode[0], inplace=True)

data['Married'].fillna(mode(data['Married']).mode[0], inplace=True)

data['Self_Employed'].fillna(mode(data['Self_Employed']).mode[0], inplace=True)

 

#Now check the #missing values again to confirm:

print data.apply(num_missing, axis=0)

 

至此,可以确定缺失值已经被填补。请注意,上述方法是最基本的填补方法。包括缺失值建模,用分组平均数(均值/众数/中位数)填补在内的其他复杂方法将在接下来的文章中进行介绍。

#4 – 数据透视表

Pandas 可建立 MS Excel 类型的数据透视表。例如在下文的代码段里,关键列“LoanAmount” 存在缺失值。我们可以根据“Gender”,“Married”和“Self_Employed”分组后的平均金额来替换。 “LoanAmount”的各组均值可由如下方法确定:

Python

1

2

3

#Determine pivot table

impute_grps = data.pivot_table(values=["LoanAmount"], index=["Gender","Married","Self_Employed"], aggfunc=np.mean)

print impute_grps

#5 – 复合索引

如果您注意观察#3计算的输出内容,会发现它有一个奇怪的性质。即每个索引均由三个数值的组合构成,称为复合索引。它有助于运算操作的快速进行。

#3的例子继续开始,已知每个分组数据值但还未进行数据填补。具体的填补方式可结合此前学到的多个技巧来完成。

Python

1

2

3

4

5

6

7

#iterate only through rows with missing LoanAmount

for i,row in data.loc[data['LoanAmount'].isnull(),:].iterrows():

  ind = tuple([row['Gender'],row['Married'],row['Self_Employed']])

  data.loc[i,'LoanAmount'] = impute_grps.loc[ind].values[0]

 

#Now check the #missing values again to confirm:

print data.apply(num_missing, axis=0)

Note:

1. 多值索引需要在 loc 语句中使用用于定义索引分组的元组结构。该元组会在函数中使用。

2. 应使用后缀 .values[0] 以避免潜在的错误。因为默认情况下复合索引返回的 Series 元素索引顺序与所在的数据框架(dataframe)不一致。在此条件下直接赋值会产生错误。

文章来自:伯乐在线

0 0