Как фильтровать строки с помощью цепочки панд?

Опубликовано: 27 Марта, 2022

В этой статье мы узнаем, как фильтровать строки с помощью цепочки Pandas. Для этого сначала мы рассмотрим некоторые предыдущие термины, которые приведены ниже:

  • Pandas DataFrame: это двухмерная структура данных, то есть данные выровнены в табличной форме по строкам и столбцам. Фрейм данных Pandas состоит из трех основных компонентов: данных, строк и столбцов.
  • Pandas Chaining: цепочка методов, при которой методы вызываются для объекта последовательно, один за другим. Это всегда был стиль программирования, который был возможен с пандами, и за последние несколько выпусков было введено множество методов, которые позволяют еще больше цепочек.

Here we use the concept of chaining in Pandas to filter the dataframe and get the same rows as an output. This can be easily explained with the help of examples. Here we use a dataframe which consists of some data of person as shown below :

Python

# 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

Выход:

Фильтр по определенному значению

Here, we select the rows with a specific value in a particular column. The Country column in dataframe is selected with value ‘India’ to filter rows.

Python3

# select the rows with specific value in 
# a particular column
print(data[data.Country.eq("India")])

Выход:

Фильтр по определенным сгруппированным значениям

Here, we select the rows with specific grouped values in a particular column. The Age column in dataframe is selected with value less than 30 to filter rows.

Python3

# select the rows with specific grouped 
# values in a particular column
print(data[data.Age<30])

Выход:

Фильтр по определенному символу или строковому значению

Here, we select the rows with specific character or string value in a particular column. The Name column in dataframe is selected with value contains ‘am’ to filter rows.

Python3

# select the rows with specific string
# or character value in a particular column
print(data[data.Name.str.contains("am")])

Выход:

Фильтр по значениям из определенного набора значений

Here, we select the rows from specific set of values in a particular column. The Country column in dataframe is selected and matched with the given set of values to filter rows.

Python3

# 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)])

Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.