📅  最后修改于: 2023-12-03 15:10:09.308000             🧑  作者: Mango
在对数据进行处理时,我们有时需要从数据帧中选择特定的行或列。通过索引操作,我们可以按照行列的标签或位置对数据帧进行过滤操作。本文将介绍如何按索引过滤数据帧。
我们可以使用loc[]
方法按行索引过滤数据帧。该方法接受一个标签或标签列表作为参数,返回符合条件的行数据,并以数据帧形式返回。
例如,我们有一个名为df
的数据帧,其中包含以下数据:
import pandas as pd
data = {'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'age': [25, 22, 21, 28, 24],
'salary': [5000, 4000, 3000, 4500, 3500]}
df = pd.DataFrame(data)
我们可以按名字索引特定的行:
selected_rows = df.loc[df['name'].isin(['Bob', 'David'])]
print(selected_rows)
输出结果为:
name age salary
1 Bob 22 4000
3 David 28 4500
我们可以使用iloc[]
方法按列索引过滤数据帧。该方法接受一个整数或整数列表作为参数,返回符合条件的列数据,并以数据帧形式返回。
例如,我们有一个名为df
的数据帧,其中包含以下数据:
import pandas as pd
data = {'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'age': [25, 22, 21, 28, 24],
'salary': [5000, 4000, 3000, 4500, 3500]}
df = pd.DataFrame(data)
我们可以按列索引取出特定的列:
selected_columns = df.iloc[:, 1:3]
print(selected_columns)
输出结果为:
age salary
0 25 5000
1 22 4000
2 21 3000
3 28 4500
4 24 3500
我们可以使用iloc[]
方法按位置索引过滤数据帧。该方法接受一个整数或整数列表作为参数,返回符合条件的行数据或列数据(根据索引类型而定),并以数据帧形式返回。
例如,我们有一个名为df
的数据帧,其中包含以下数据:
import pandas as pd
data = {'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'age': [25, 22, 21, 28, 24],
'salary': [5000, 4000, 3000, 4500, 3500]}
df = pd.DataFrame(data)
我们可以按位置索引取出特定的行和列:
selected_rows_and_columns = df.iloc[1:4, 1:3]
print(selected_rows_and_columns)
输出结果为:
age salary
1 22 4000
2 21 3000
3 28 4500
以上就是按索引过滤数据帧的方法,我们可以根据自己的需要选择不同的过滤方式,以达到数据处理的目的。