python - 无法从数据框中清除 NaN 行

标签 python pandas

所以,我正在尝试清理包含一些 NaN 值的数据框

我尝试了所有建议的方法,但似乎我无法摆脱 NaN。

df = pd.read_csv('filename.tsv', delimiter='\t')
df = df[pd.notnull(df)]
df = df.dropna()

df[pd.isnull(df)]
# gives our records containing NaN (alot of them.)

我不确定我错过了什么?

编辑: 给出 NaN 的列的所有列都为 NaN enter image description here

更多编辑: 当我尝试查看类型时

heads =  df[df.isnull()].head()
for idx, row in heads.iterrows():
    print idx, type(row.listener_id)

本次返回

0 <type 'float'>
1 <type 'float'>
2 <type 'float'>
3 <type 'float'>
4 <type 'float'>

最佳答案

我认为如果需要使用 bool 索引:

df = df[~df.isnull().any(axis=1)]

但更好的是仅使用:

df = df.dropna()

示例:

df = pd.DataFrame({'A':[np.nan,5,4,5,5,np.nan],
                   'B':[7,8,9,4,2,np.nan],
                   'C':[1,3,5,7,1,np.nan],
                   'D':[5,3,6,9,2,np.nan]})

print (df)
     A    B    C    D
0  NaN  7.0  1.0  5.0
1  5.0  8.0  3.0  3.0
2  4.0  9.0  5.0  6.0
3  5.0  4.0  7.0  9.0
4  5.0  2.0  1.0  2.0
5  NaN  NaN  NaN  NaN
<小时/>
#get True for NaN
print (df.isnull())
       A      B      C      D
0   True  False  False  False
1  False  False  False  False
2  False  False  False  False
3  False  False  False  False
4  False  False  False  False
5   True   True   True   True

#check at least one True per row
print (df.isnull().any(axis=1))
0     True
1    False
2    False
3    False
4    False
5     True
dtype: bool

#boolen indexing with inverting `~` (need select NO NaN rows)
print (df[~df.isnull().any(axis=1)])
     A    B    C    D
1  5.0  8.0  3.0  3.0
2  4.0  9.0  5.0  6.0
3  5.0  4.0  7.0  9.0
4  5.0  2.0  1.0  2.0
<小时/>
#get True for not NaN
print (df.notnull())
       A      B      C      D
0  False   True   True   True
1   True   True   True   True
2   True   True   True   True
3   True   True   True   True
4   True   True   True   True
5  False  False  False  False

#get True if all values per row are True 
print (df.notnull().all(axis=1))
0    False
1     True
2     True
3     True
4     True
5    False
dtype: bool

#boolean indexing
print (df[df.notnull().all(axis=1)])
     A    B    C    D
1  5.0  8.0  3.0  3.0
2  4.0  9.0  5.0  6.0
3  5.0  4.0  7.0  9.0
4  5.0  2.0  1.0  2.0
<小时/>
#simpliest solution
print (df.dropna())
     A    B    C    D
1  5.0  8.0  3.0  3.0
2  4.0  9.0  5.0  6.0
3  5.0  4.0  7.0  9.0
4  5.0  2.0  1.0  2.0

关于python - 无法从数据框中清除 NaN 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46048692/

相关文章:

python - 如何将分钟添加到 Pandas Dataframe 中的 datetime64 对象

python - Groupby 与用户定义的函数 Pandas

gcc - 在AWS中安装Pandas时出错

python - aioredis + aiohttp 正确使用连接池

python - Scikit-Learn:如何检索 KFold CV 的预测概率?

python - Matplotlib:颜色条的高度与绘图的高度相同

python - FastAPI 中的中间件,用于为每个请求生成 UUID 并发送到日志

java - 如何使用 Scala/Java 中的索引从另一个数组分配一个数组的元素?

python - 创建用于数据框的函数

python - 从首字母为小写的数据框中删除行