Удалить бесконечные значения из заданного фрейма данных Pandas

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

Давайте обсудим, как удалить бесконечные значения из фрейма данных Pandas. Сначала создадим фрейм данных:

Example:

Python3

# Import Required Libraries
import pandas as pd
import numpy as np
  
# Create a dictionary for the dataframe
dict = {"Name": ["Sumit Tyagi", "Sukritin", "Akriti Goel",
                 "Sanskriti", "Abhishek Jain"],
        "Age": [22, 20, np.inf, -np.inf, 22], 
        "Marks": [90, 84, 33, 87, 82]}
  
# Converting Dictionary to Pandas Dataframe
df = pd.DataFrame(dict)
  
# Print Dataframe
df

Выход:

Метод 1. Замена бесконечности на Nan, а затем отбрасывание строк с помощью Nan.

We will first replace the infinite values with the NaN values and then use the dropna() method to remove the rows with infinite values. df.replace() method takes 2 positional arguments. First is the list of values you want to replace and second with which value you want to replace the values. 
 

Python3

# Replacing infinite with nan
df.replace([np.inf, -np.inf], np.nan, inplace=True)
  
# Dropping all the rows with nan values
df.dropna(inplace=True)
  
# Printing df
df

Выход:

Метод 2: изменение параметра Pandas, чтобы оно считалось бесконечным как Nan

Панды предоставляют возможность использовать бесконечность как Нан. Это заставляет весь модуль pandas рассматривать бесконечные значения как nan. Мы можем сделать это с помощью pd.set_option (). Он устанавливает параметр глобально во всем блокноте Jupyter.
Синтаксис:

 pd.set_option ('mode.use_inf_as_na', Истина)

It sets the options to use infinite as a Nan value throughout the session or until the options are not set back to the False.  

Python3

# Changing option to use infinite as nan
pd.set_option("mode.use_inf_as_na", True)
  
# Dropping all the rows with nan values
df.dropna(inplace=True)
  
# Printing df
df

Выход:

Метод 3: рассматривать бесконечность как Nan, но использовать option_context

Instead of using pd.set_options(), which sets the option globally, we can use pd.option_context(), which changes option within the certain scope only.
 

Python3

# Changing option to use infinite as nan
with pd.option_context("mode.use_inf_as_na", True):
    
    # Dropping the rows with nan 
    # (or inf) values
    df.dropna(inplace=True)
  
# Printing df
df

Выход:

Метод 4: Использование фильтра

We will first create a filter which returns a boolean dataframe and use this filter to mask the infinite values.  

Python3

# Creating filter
df_filter = df.isin([np.nan, np.inf, -np.inf])
  
# Masking df with the filter
df = df[~df_filter]
  
# Dropping rows with nan values
df.dropna(inplace=True)
  
# Printing df
df

Выход:

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

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