![]() |
|
[Tut] Pandas NaN — Working With Missing Data - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Pandas NaN — Working With Missing Data (/thread-98113.html) |
[Tut] Pandas NaN — Working With Missing Data - xSicKxBot - 11-04-2020 Pandas NaN — Working With Missing Data Pandas is Excel on steroids—the powerful Python library allows you to analyze structured and tabular data with surprising efficiency and ease. Pandas is one of the reasons why master coders reach 100x the efficiency of average coders. In today’s article, you’ll learn how to work with missing data—in particular, how to handle NaN values in Pandas DataFrames. You’ll learn about all the different reasons why NaNs appear in your DataFrames—and how to handle them. Let’s get started! Checking Series for NaN Values Problem: How to check a series for NaN values? Have a look at the following code: Code: import pandas as pd
import numpy as np data = pd.Series([0, np.NaN, 2])
result = data.hasnans print(result)
# TrueSeries can contain Code: NaNTo check if a Series contains one or more Code: NaNCode: hasnansCode: TrueCode: NaNCode: FalseThere’s a Code: NaNCode: TrueFiltering Series Generates NaN Problem: When filteringa Series with Code: where()Code: import pandas as pd xs = pd.Series([5, 1, 4, 2, 3])
xs.where(xs > 2, inplace=True)
result = xs.hasnans print(result)
# TrueThe method Code: where()Code: NaNThis is why our Series contains Code: NaNCode: where()Working with Multiple Series of Different Lengths Problem: If you element-wise add two Series objects with a different number of elements—what happens with the remaining elements? Code: import pandas as pd s = pd.Series(range(0, 10))
t = pd.Series(range(0, 20))
result = (s + t)[1] print(result)
# 2To add two Series element-wise, use the default addition operator Code: +Code: NaNAt index Code: 1Code: 1 + 1 = 2Create a DataFrame From a List of Dictionaries with Unequal Keys Problem: How to create a DataFrame from a list of dictionaries if the dictionaries have unequal keys? A DataFrame expects the same columns to be available for each row! Code: import pandas as pd data = [{'Car':'Mercedes', 'Driver':'Hamilton, Lewis'}, {'Car':'Ferrari', 'Driver':'Schumacher, Michael'}, {'Car':'Lamborghini'}] df = pd.DataFrame(data, index=['Rank 2', 'Rank 1', 'Rank 3'])
df.sort_index(inplace=True)
result = df['Car'].iloc[0] print(result)
# FerrariYou can create a DataFrame from a list of dictionaries. The dictionaries’ keys define the column labels, and the values define the columns’ entries. Not all dictionaries must contain the same keys. If a dictionary doesn’t contain a particular key, this will be interpreted as a Code: NaNThis code snippet uses string labels as index values to sortthe DataFrame. After sorting the DataFrame, the row with index label Code: Rank 1Code: CarCode: FerrariSorting a DataFrame by Column with NaN Values Problem: What happens if you sort a DataFrame by column if the column contains a Code: NaNCode: import pandas as pd df = pd.read_csv("Cars.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- selection = df.sort_values(by="engine-size")
result = selection.index.to_list()[0]
print(result)
# 1In this code snippet, you sort the rows of the DataFrame by the values of the column Code: engine-sizeThe main point is that Code: NaNCode: 1.8Code: 1Count Non-NaN Values Problem: How to count the number of elements in a dataframe column that are not Code: NanCode: import pandas as pd df = pd.read_csv("Cars.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- df.count()[5]
print(result)
# 4The method Code: count()Code: NaNCode: dfcontains one Code: NaNCode: 4Drop NaN-Values Problem: How to drop all rows that contain a Code: NaNCode: import pandas as pd df = pd.read_csv("Cars.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- selection1 = df.dropna(subset=["price"])
selection2 = df.dropna()
print(len(selection1), len(selection2))
# 5 4The DataFrame’s Code: dropna()Code: NaNCode: NaNBy passing a list of column labels to the optional parameter Code: subsetThe call of Code: dropna()Code: 2Code: NaNCode: engine-sizeCode: priceCode: NaNDrop Nan and Reset Index Problem: What happens to indices after dropping certain rows? Code: import pandas as pd df = pd.read_csv("Cars.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- df.drop([0, 1, 2], inplace=True)
df.reset_index(inplace=True)
result = df.index.to_list()
print(result)
# [0, 1]The method Code: drop()By default the Code: inplaceCode: FalseCode: inplaceCode: TrueAfter deleting the first three rows, the first two index labels are 3 and 4. You can reset the default indexing by calling the method Code: reset_index()Code: [0, 1]Concatenation of Dissimilar DataFrames Filled With NaN Problem: How to concatenate two DataFrames if they have different columns? Code: import pandas as pd df = pd.read_csv("Cars.csv")
df2 = pd.read_csv("Cars2.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- # Additional Dataframe "df2"
# ----------
# make origin
# 0 skoda Czechia
# 1 toyota Japan
# 2 ford USA
# ---------- try: result = pd.concat([df, df2], axis=0, ignore_index=True) print("Y")
except Exception: print ("N") # YEven if DataFrames have different columns, you can concatenate them. If DataFrame 1 has columns A and B and DataFrame 2 has columns C and D, the result of concatenating DataFrames 1 and 2 is a DataFrame with columns A, B, C, and D. Missing values in the rows are filled with Code: NaNOuter Merge Problem: When merging (=joining) two DataFrames—what happens if there are missing values? Code: import pandas as pd df = pd.read_csv("Cars.csv")
df2 = pd.read_csv("Cars2.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- # Additional dataframe "df2"
# ----------
# make origin
# 0 skoda Czechia
# 1 mazda Japan
# 2 ford USA
# ---------- result = pd.merge(df, df2, how="outer", left_on="make", right_on="make")
print(len(result["fuel"]))
print(result["fuel"].count())
# 7
# 5With Panda’s function Code: merge()Code: howCode: outerThe resulting DataFrame of an outer join contains all values from both input DataFrames; missing values are filled with Code: NaNIn addition, this puzzle shows how Code: NaNCode: len()Code: count()Code: NaNReplacing NaN Problem: How to Replace all Code: NaNCode: import pandas as pd df = pd.read_csv("Cars.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- df.fillna(2.0, inplace=True)
result = df["engine-size"].sum()
print(result)
# 13.8The method Code: fillna()Code: NaNCode: engine-sizeLength vs. Count Difference — It’s NaN! Problem: What’s the difference between the Code: len()Code: count()Code: import pandas as pd df = pd.read_csv("Cars.csv")
df2 = pd.read_csv("Cars2.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- # Additional dataframe "df2"
# ----------
# make origin
# 0 skoda Czechia
# 1 mazda Japan
# 2 ford USA
# ---------- result = pd.merge(df2, df, how="left", left_on="make", right_on="make")
print(len(result["fuel"]))
print(result["fuel"].count())
# 3
# 1In a left join, the left DataFrame is the master, and all its values are included in the resulting DataFrame. Therefore, the result DataFrame contains three rows, yet, since Code: skodaCode: fordCode: dfCode: mazdaAgain, we see the difference between using the function Code: len()Code: NaNCode: count()Code: NaNEquals() vs. == When Comparing NaN Problem: Code: import pandas as pd df = pd.read_csv("Cars.csv") # Dataframe "df"
# ----------
# make fuel aspiration body-style price engine-size
# 0 audi gas turbo sedan 30000 2.0
# 1 dodge gas std sedan 17000 1.8
# 2 mazda diesel std sedan 17000 NaN
# 3 porsche gas turbo convertible 120000 6.0
# 4 volvo diesel std sedan 25000 2.0
# ---------- df["engine-size_copy"] = df["engine-size"]
check1 = (df["engine-size_copy"] == df["engine-size"]).all()
check2 = df["engine-size_copy"].equals(df["engine-size"])
print(check1 == check2)
# FalseThis code snippet shows how to compare columns or entire DataFrames regarding the shape and the elements. The comparison using the operator Code: ==Code: FalseCode: NaNCode: ==Code: FalseOn the other hand, Code: df.equals()Code: NaNThe column headers do not need to have the same type, but the elements within the columns must be of the same Code: dtypeSince the result of Code: check1Code: FalseCode: check2Code: TrueCode: FalseWhere to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! The post Pandas NaN — Working With Missing Data first appeared on Finxter. |