Python Pandas - 删除nans时的问题

24 浏览
0 Comments

Python Pandas - 删除nans时的问题

这个问题已经有了解答:

如何删除 Pandas DataFrame 中某一列值为 NaN 的行

我正在努力删除 NaN。已经花了一些时间寻找解决方法,但似乎没有什么作用。

下面我会附上我的代码样例,完整的笔记本可以在我的 GitHub 这里找到:https://github.com/jarsonX/Temp_files/blob/main/W3-Exploratory%20Data%20Analysis(1).ipynb

import pandas as pd     
import seaborn as sns               #not used in this sample, needed for plotting later on
import matplotlib as mpl            #as above
import matplotlib.pyplot as plt     #as above
import numpy as np                  #as above
df = pd.read_csv("https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DA0321EN-SkillsNetwork/LargeData/m2_survey_data.csv")
df.Age.describe()  #dtype float64
df['Age'].isna().value_counts()  #287 nans
df['Age'].dropna(how='any', inplace=True)  #trying to remove nans
df['Age'].isna().value_counts()  #still 287 nans
#Just for the sake of identification of rows
#I tried to print ONLY nans but could not figure out how to do it.
i = 0
for el in df.Age:
    print(i, el, type(el))
    i += 1
#The first nan is in the 67th row

我错过了什么吗?

更新:

我成功地筛选出了 NaN:

i = 0
for el in df.Age:
    if el != el:
        print(i, el, type(el))
    i += 1

admin 更改状态以发布 2023年5月24日
0
0 Comments

这应该可以工作:

df = df[~df['Age'].isnull()]

~运算符可以用作否定
验证是否已删除nans

df ['Age'].isna().value_counts()

0
0 Comments

您可以尝试以下代码片段,dropna在Series中调用时不会遵守how参数,因为它只是一个单一的列。

df.dropna(subset=["Age"], how="any", inplace=True)

0