Удалить бесконечные значения из заданного фрейма данных Pandas
Давайте обсудим, как удалить бесконечные значения из фрейма данных Pandas. Сначала создадим фрейм данных:
Example:
Python3
# Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {"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 Dataframedf = pd.DataFrame(dict) # Print Dataframedf |
Выход:

Метод 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 nandf.replace([np.inf, -np.inf], np.nan, inplace=True) # Dropping all the rows with nan valuesdf.dropna(inplace=True) # Printing dfdf |
Выход:

Метод 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 nanpd.set_option("mode.use_inf_as_na", True) # Dropping all the rows with nan valuesdf.dropna(inplace=True) # Printing dfdf |
Выход:

Метод 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 nanwith pd.option_context("mode.use_inf_as_na", True): # Dropping the rows with nan # (or inf) values df.dropna(inplace=True) # Printing dfdf |
Выход:

Метод 4: Использование фильтра
We will first create a filter which returns a boolean dataframe and use this filter to mask the infinite values.
Python3
# Creating filterdf_filter = df.isin([np.nan, np.inf, -np.inf]) # Masking df with the filterdf = df[~df_filter] # Dropping rows with nan valuesdf.dropna(inplace=True) # Printing dfdf |
Выход:

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