Python | Серия Pandas / Dataframe.any ()

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

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

Pandas any() method is applicable both on Series and Dataframe. It checks whether any value in the caller object (Dataframe or series) is not 0 and returns True for that. If all values are 0, it will return False.

Syntax: DataFrame.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)

Parameters:
axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columns.
bool_only: Checks for bool only series in Data frame, if none found, it will use only boolean values. This parameter is not for series since there is only one column.
skipna: Boolean value, If False, returns True for whole NaN column/row
level: int or str, specifies level in case of multilevel

Return type: Boolean series

Пример # 1: реализация с разумным индексом

In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method. Null values are also passed to some indexes using Numpy np.nan to check behaviour with null values. Since in this example, the method is implemented on index, the axis parameter is kept 0 (that stands for rows).

# importing pandas module 
import pandas as pd 
  
# importing numpy module
import numpy as np
  
# creating dictionary
dic = {"A": [1, 2, 3, 4, 0, np.nan, 3],
       "B": [3, 1, 4, 5, 0, np.nan, 5],
       "C": [0, 0, 0, 0, 0, 0, 0]}
  
# making dataframe using dictionary
data = pd.DataFrame(dic)
  
# calling data.any column wise
result = data.any(axis = 0)
  
# displaying result
result

Выход:
Как показано в выходных данных, поскольку все значения последнего столбца равны нулю, False было возвращено только для этого столбца.


Пример # 2: реализация по столбцам

In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method just like in above example. But instead of passing 0 to axis parameter, 1 is passed to implement for each value in every column.

# importing pandas module 
import pandas as pd 
  
# importing numpy module
import numpy as np
  
# creating dictionary
dic = {"A": [1, 2, 3, 4, 0, np.nan, 3],
       "B": [3, 1, 4, 5, 0, np.nan, 5],
       "C": [0, 0, 0, 0, 0, 0, 0]}
  
# making dataframe using dictionary
data = pd.DataFrame(dic)
  
# calling data.any column wise
result = data.any(axis = 1)
  
# displaying result
result

Выход:
Как показано в выходных данных, False было возвращено только для строк, все значения которых были 0 или NaN и 0.

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

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