如何使用Pandas Chaining过滤行
在这篇文章中,我们将学习如何使用Pandas链来过滤行。为此,我们首先要看一下以前的一些术语,下面给出了这些术语。
- Pandas DataFrame:它是一个二维数据结构,即数据以表格形式排列在行和列中。Pandas DataFrame有三个主要部分,即数据、行和列。
- Pandas链式。方法链,即在一个对象上依次调用方法,一个接一个。这一直是pandas可以实现的一种编程风格,在过去的几个版本中,引入了许多方法,允许更多的链式编程。
使用Pandas Chaining创建数据框架来过滤行
# import package
import pandas as pd
# define data
data = pd.DataFrame(
{'ID': {0: 105, 1: 102, 2: 101, 3: 106, 4: 103, 5: 104, 6: 107},
'Name': {0: 'Ram Kumar', 1: 'Jack Wills', 2: 'Deepanshu Rustagi',
3: 'Thomas James', 4: 'Jenny Advekar', 5: 'Yash Raj',
6: 'Raman Dutt Mishra'},
'Age': {0: 40, 1: 23, 2: 20, 3: 34, 4: 18, 5: 56, 6: 35},
'Country': {0: 'India', 1: 'Uk', 2: 'India', 3: 'Australia',
4: 'Uk', 5: 'India', 6: 'India'}
})
# view data
data
输出:
按特定值过滤
方法1:使用eq过滤行
在这里,我们选择在某一特定列中具有特定值的行。数据框架中的国家列被选择为 “印度”,以过滤行。
# select the rows with specific value in
# a particular column
print(data[data.Country.eq('India')])
输出:
方法2:使用管道过滤行
在这里,我们选择在某一特定列中具有特定值的行。数据框架中的国家列被选择为 “印度”,以使用管道过滤行。
# Using pipe() method
df2 = data.pipe(lambda x: x['Country'] == "India")
print(df2)
输出:
0 True
1 False
2 True
3 False
4 False
5 True
6 True
Name: Country, dtype: bool
通过特定的分组值进行过滤
方法1:使用手动给出的索引值过滤行
在这里,我们选择在某一列中具有特定分组值的行。数据框架中的年龄列被选择为小于30的值来过滤行。
# select the rows with specific grouped
# values in a particular column
print(data[data.Age<30])
输出:
方法2:使用loc过滤行
在这里,我们选择在某一列中具有特定分组值的行。数据框架中的ID和年龄列被选择为小于等于103的值和等于23的年龄来过滤行。
# Chaining loc[] operator to filter rows
df2 = data.loc[lambda x: x['ID'] <=
103].loc[lambda x: x['Age'] == 23]
print(df2)
输出:
ID Name Age Country
1 102 Jack Wills 23 Uk
方法3:使用掩码过滤行
在这里,我们选择在某一列中具有特定分组值的行。数据框架中的年龄列被选择为大于等于39的值来过滤行。
# Using mask and lambda function to filter
df2 = data.mask(lambda x: x['Age'] <= 39)
df2 = df2.dropna()
print(df2)
输出:
ID Name Age Country
0 105.0 Ram Kumar 40.0 India
5 104.0 Yash Raj 56.0 India
通过特定的字符或一组特定的值进行过滤
方法1:使用contains过滤行
在这里,我们选择在某一列中具有特定字符或字符串值的行。Dataframe中的Name列被选择为包含’am’的值来过滤行。
# select the rows with specific string
# or character value in a particular column
print(data[data.Name.str.contains('am')])
输出:
方法2:使用isin过滤行
在这里,我们从某一列的特定值集合中选择行。Dataframe中的国家列被选中,并与给定的值集相匹配以过滤行。
# define the set of values
lst=['Uk','Australia']
# select the rows from specific set
# of values in a particular column
print(data[data.Country.isin(lst)])
输出: