Python | Панды dataframe.eq ()

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

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas dataframe.eq() is a wrapper used for the flexible comparison. It provides a convenient way to perform comparison of dataframe object with constant, series or another dataframe object.

Syntax: DataFrame.eq(other, axis=’columns’, level=None)

Parameters:
other : Series, DataFrame, or constant
axis : {0, 1, ‘index’, ‘columns’}
level : None by default

Returns: result : DataFrame containing boolean values

Example #1: Use eq() function to find the result of comparison between a dataframe and a constant.

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe with NaN value
df = pd.DataFrame({"A":[5, 3, None, 4],
                   "B":[None, 2, 4, 3],
                   "C":[4, 3, 8, 5],
                   "D":[5, 4, 2, None]})
  
# Print the dataframe
df

Now find the comparison of the dataframe element with value 2.

# To find the comparison result
df.eq(2)

Выход :

The output is a dataframe with cells containing the result of the comparison. True value indicating that the cell value is equal to the comparison value and False indicating non-equal value being compared. Notice, how missing values are evaluated to be false. If we compare two NaN using equality operator then the result will be false.
 

Example #2: Use eq() function to test for equality between a data frame object and a series object

# importing pandas as pd
import pandas as pd
  
# Creating the dataframe 
df = pd.DataFrame({"A":[5, 3, 6, 4],
                   "B":[11, 2, 4, 3],
                   "C":[4, 3, 8, 5],
                   "D":[5, 4, 2, 8]})
  
# Print the dataframe
df

Теперь создайте объект серии с номером. элементов, равных элементу по оси индекса.

Note: If the dimension of the index axis of the dataframe and the series object is not same then an error will occur.

# Creating a pandas series object
series_object = pd.Series([11, 3, 4, 8])
  
# Print the series_obejct
series_object

Now, find the comparison between the dataframe object and the series object along the index axis. The dimension of the series and the dataframe axis being taken for comparison should be same.

# To find the comparison between 
# dataframe and the series object.
df.eq(series_object, axis = 0)

Выход :

Результатом является фрейм данных с ячейками, содержащий результат сравнения текущего элемента ячейки с соответствующей ячейкой объекта серии.

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

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