Python | Pandas Index.fillna ()

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

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

Pandas Index.fillna() function fill NA/NaN values with the specified value. It only takes a scalar value to be filled for all the missing vales present in the Index. The function returns a new object having the missing values filled by the passed value.

Syntax: Index.fillna(value=None, downcast=None)

Parameters :
value : Scalar value to use to fill holes (e.g. 0). This value cannot be a list-likes.
downcast : a dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible)

Returns : filled : %(klass)s

Example #1: Use Index.fillna() function to fill all the missing values in the the Index.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index([1, 2, 3, 4, 5, None, 7, 8, 9, None])
  
# Print the Index
idx

Выход :

Let’s fill all the missing values in the Index with -1.

# fill na values with -1
idx.fillna(-1)

Output :

As we can see in the output, the Index.fillna() function has filled all the missing values with -1. The function only takes scalar value.
 
Example #2: Use Index.fillna() function to fill all the missing strings in the Index.

# importing pandas as pd
import pandas as pd
  
# Creating the Index
idx = pd.Index(["Labrador", "Beagle", None, "Labrador"
             "Lhasa", "Husky", "Beagle", None, "Koala"])
  
# Print the Index
idx

Output :

As we can see in the output we are having some missing values. For the purpose of data analysis, we would like to fill these missing values with some other indicative values which serves our purpose.

# Fill the missing values by "Value_Missing"
idx.fillna("Value_Missing")

Выход :

Как видно из выходных данных, все недостающие строки в индексе были заполнены переданными значениями.

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

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