Python干货:panda特殊索引器——过滤数据

166 阅读4分钟

迄今为止最常见从DataFrame获取元素、行和列的数据索引方式:

  • **Dataframe.[];**此函数也称为索引运算符。
  • **Dataframe.loc[] :**此函数用于标签。
  • **Dataframe.iloc[] :**此函数用于基于位置或整数的
  • **Dataframe.ix[] :**此函数用于标号和基于整数的函数。
![](https://p26-tt.byteimg.com/origin/pgc-image/6067f0a2eac0460a9616773eafcd70f4)

它们统称为索引器。而布尔索引是一种索引类型,它使用DataFrame中数据的实际值。

它们统称为索引器。而布尔索引是一种索引类型,它使用DataFrame中数据的实际值。

根据DataFrame中数据的实际值而不是它们的行/列标签或整数位置来选择数据子集。

在布尔索引中使用布尔向量过滤数据,通过四种方式过滤数据:

  • 使用布尔索引访问DataFrame
  • 将布尔掩码应用于数据帧
  • 基于列值的掩蔽数据
  • 基于索引值的掩蔽数据

使用布尔索引访问DataFrame:

创建一个dataframe,其中的dataframe索引包含一个布尔值。即“True”或“false”。例如

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

df = pd.DataFrame(dict, index = [True, False, True, False])

print(df)

产出:

![](https://p1.pstatp.com/origin/pgc-image/a082eed76c894fa99bd2f84ac74a00c7)

借助布尔索引访问数据,使用以下三个函数访问数据文件.loc[], .iloc[], .ix[]

使用布尔索引访问Dataframe.loc[]

访问具有布尔索引的数据,使用.loc[],将布尔值(真或假)传递给.loc[]功能。

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe with boolean index 
df = pd.DataFrame(dict, index = [True, False, True, False])

# accessing a dataframe using .loc[] function 
print(df.loc[True])

产出:

![](https://p1-tt-ipv6.byteimg.com/origin/pgc-image/f2237a63249441da8128e05cfdedd977)

使用布尔索引访问Dataframe.iloc[]

使用.iloc[]访问数据文件,在iloc[]功能但iloc[]函数只接受整数作为参数。
代码1:

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe with boolean index  
df = pd.DataFrame(dict, index = [True, False, True, False])

# accessing a dataframe using .iloc[] function 
print(df.iloc[True])

产出:

TypeError 

代码2:

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe with boolean index  
df = pd.DataFrame(dict, index = [True, False, True, False])

# accessing a dataframe using .iloc[] function
print(df.iloc[1])

产出:

![](https://p6-tt-ipv6.byteimg.com/origin/pgc-image/6191b70c916a4450b26e8a301e429a98)

使用布尔索引访问Dataframe.ix[]

使用.ix[]访问数据文件,.ix[]函数是.loc[]和.iloc[]功能,将布尔值(真或假)和整数值传递给.ix[]。
代码1:

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe with boolean index
df = pd.DataFrame(dict, index = [True, False, True, False])

# accessing a dataframe using .ix[] function
print(df.ix[True])

产出:

![](https://p3-tt-ipv6.byteimg.com/origin/pgc-image/0f0f5d78456b498f8db7817ebd75e0b6)

代码2:

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe with boolean index 
df = pd.DataFrame(dict, index = [True, False, True, False])

# accessing a dataframe using .ix[] function
print(df.ix[1])

产出:

![](https://p6-tt-ipv6.byteimg.com/origin/pgc-image/33d9a02bc39249b4b698661f284f0d52)

将布尔掩码应用于dataframe:

应用一个布尔掩码,它将只打印传递布尔值True的数据,使用__getitems__或[]访问。

用dataframe中包含的长度相同的真假列表来应用布尔掩码,

代码1:

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["MBA", "BCA", "M.Tech", "MBA"],
        'score':[90, 40, 80, 98]}

df = pd.DataFrame(dict, index = [0, 1, 2, 3])

print(df[[True, False, True, False]])

产出:

![](https://p9-tt-ipv6.byteimg.com/origin/pgc-image/1c92716ffbd74f10b778d52b8b513ed8)

代码2:

# importing pandas package
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba1.1.csv")

df = pd.DataFrame(data, index = [0, 1, 2, 3, 4, 5, 6,
                                 7, 8, 9, 10, 11, 12])

df[[True, False, True, False, True,
    False, True, False, True, False,
                True, False, True]]

产出:

![](https://p1.pstatp.com/origin/pgc-image/1d75880879d24b1fa1502d37133839d8)

基于列值的掩蔽数据:
在dataframe中,使用不同的运算符(如==, >, <, <=, >=)根据列值对数据进行过滤。

代码1:

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["BCA", "BCA", "M.Tech", "BCA"],
        'score':[90, 40, 80, 98]}

# creating a dataframe 
df = pd.DataFrame(dict)

# using a comparison operator for filtering of data
print(df['degree'] == 'BCA')

产出:

![](https://p6-tt-ipv6.byteimg.com/origin/pgc-image/af49e479624a4cf8b862c15e644a375a)

代码2:

# importing pandas package
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba.csv", index_col ="Name")

# using greater than operator for filtering of data
print(data['Age'] > 25)

产出:

![](https://p1.pstatp.com/origin/pgc-image/8b6d272774264989a4f5b4a7fea55da0)

基于索引值的掩蔽数据:
在dataframe中,使用不同的运算符创建基于索引值的掩码 ==, >, <

代码1:

# importing pandas as pd
import pandas as pd

# dictionary of lists
dict = {'name':["aparna", "pankaj", "sudhir", "Geeku"],
        'degree': ["BCA", "BCA", "M.Tech", "BCA"],
        'score':[90, 40, 80, 98]}

df = pd.DataFrame(dict, index = [0, 1, 2, 3])

mask = df.index == 0

print(df[mask])

产出:

![](https://p26-tt.byteimg.com/origin/pgc-image/8b8334428f1147f0b207612788acbbc2)

代码2:

# importing pandas package
import pandas as pd

# making data frame from csv file
data = pd.read_csv("nba1.1.csv")

# giving a index to a dataframe
df = pd.DataFrame(data, index = [0, 1, 2, 3, 4, 5, 6,
                                 7, 8, 9, 10, 11, 12])

# filtering data on index value
mask = df.index > 7 

df[mask]

产出:

![](https://p1.pstatp.com/origin/pgc-image/d1402ef825ab4f5b897da2ad3b5ac7ab)