作者|Amanda Iglesias Moreno 编译|VK 来源|Towards Datas Science
从数据帧中过滤数据是清理数据时最常见的操作之一。Pandas提供了一系列根据行和列的位置和标签选择数据的方法。此外,Pandas还允许你根据列类型获取数据子集,并使用布尔索引筛选行。
在本文中,我们将介绍从Pandas数据框中选择数据子集的最常见操作:
- 按标签选择单列
- 按标签选择多列
- 按数据类型选择列
- 按标签选择一行
- 按标签选择多行
- 按位置选择一行
- 按位置选择多行
- 同时选择行和列
- 选择标量值
- 使用布尔选择选择选择行
另外,我们将提供多个编码示例!

数据集
在本文中,我们使用一个小数据集进行学习。在现实世界中,所使用的数据集要大得多;然而,用于过滤数据的过程保持不变。
数据框包含公司10名员工的信息:(1)身份证,(2)姓名,(3)姓氏,(4)部门,(5)电话,(6)工资,(7)合同类型。
import pandas as pd# 员工的信息
id_number = ['128', '478', '257', '299', '175', '328', '099', '457', '144', '222']
name = ['Patrick', 'Amanda', 'Antonella', 'Eduard', 'John', 'Alejandra', 'Layton', 'Melanie', 'David', 'Lewis']
surname = ['Miller', 'Torres', 'Brown', 'Iglesias', 'Wright', 'Campos', 'Platt', 'Cavill', 'Lange', 'Bellow']
division = ['Sales', 'IT', 'IT', 'Sales', 'Marketing', 'Engineering', 'Engineering', 'Sales', 'Engineering', 'Sales']
salary = [30000, 54000, 80000, 79000, 15000, 18000, 30000, 35000, 45000, 30500]
telephone = ['7366578', '7366444', '7366120', '7366574', '7366113', '7366117', '7366777', '7366579', '7366441', '7366440']
type_contract = ['permanent', 'temporary', 'temporary', 'permanent', 'internship', 'internship', 'permanent', 'temporary', 'permanent', 'permanent']# 包含员工信息的dataframe
df_employees = pd.DataFrame({'name': name, 'surname': surname, 'division': division,'salary': salary, 'telephone': telephone, 'type_contract': type_contract}, index=id_number)df_employees
1.按标签选择单列
要在Pandas中选择一个列,我们可以使用.运算符和[]运算符。
按标签选择单列
df[string]下面的代码使用这两种方法访问salary列。
# 使用.符号选择列(salary)
salary = df_employees.salary# 使用方括号选择列(salary)
salary_2 = df_employees['salary']# 当选择单个列时,我们获得一个Series对象
print(type(salary))
# <class 'pandas.core.series.Series'>print(type(salary_2))
# <class 'pandas.core.series.Series'>salary
如上所示,当检索单个列时,结果是一个Series对象。为了在只选择一列时获得一个DataFrame对象,我们需要传入一个列表,而不仅仅是一个字符串。
# 通过向索引操作符传递一个字符串来获取一个Series对象
df_employees['salary']# 通过将带有单个项的列表传递给索引操作符来获取DataFrame对象
df_employees[['salary']]
此外,重要的是要记住,当列名包含空格时,我们不能使用.表示法来访问数据帧的特定列。如果我们这么做了,就会产生一个语法错误。
2.按标签选择多列
我们可以通过传入一个列名称如下的列表来选择一个数据帧的多个列。
按标签选择多列
df[list_of_strings]# 通过将包含列名的列表传递给
















