在 DataFrame 中找出有空值的行(两种情况)

一、对于空值是NaN的情况

1.找出含有空值的行

方法:DataFrame[DataFrame.isnull().T.any()]

其中,isnull()能够判断数据中元素是否为空值;

T为转置;

any()判断该行是否有空值。

import pandas as pd
import numpy as np

n = np.arange(20, dtype=float).reshape(5,4)
n[2,3] = np.nan
index = ['index1', 'index2', 'index3', 'index4', 'index5']
columns = ['column1', 'column2', 'column3', 'column4']
frame3 = pd.DataFrame(data=n, index=index, columns=columns)
print(frame3)
print("==========有空值==========")
print(frame3[frame3.isnull().T.any()])

输出结果:

        column1  column2  column3  column4
index1      0.0      1.0      2.0      3.0
index2      4.0      5.0      6.0      7.0
index3      8.0      9.0     10.0      NaN
index4     12.0     13.0     14.0     15.0
index5     16.0     17.0     18.0     19.0
==========有空值==========
        column1  column2  column3  column4
index3      8.0      9.0     10.0      NaN

程序成功找到了第三行为有空值的行。

2.为什么加转置

在代码中,isnull()的结果需要求转置之后,才能进行any()操作,这是为什么呢?

下面对比一下isnull转置和非转置的情况:

print(frame3.isnull().any())
print("========================")
print(frame3.isnull().T.any())

可见:

非转置:frame3.isnull().any(),得到的每一列求any()计算的结果,输出为列的Series。

转置:frame3.isnull().T.any(),得到的每一行求any()计算的结果,输出为行的Series。

二、对于空值是空白字符,包括空格、制表符、换页符等的情况

如果是这种情况,用isnull判断的时候也是为False的。为什么会有这样的情况呢,原来在pandas里空值是指NA,包括numpy的np.nan,python的None,pandas对空值进行操作可以用isnull/notnull/isna/notna/fillna/dropna等等,但是,这些操作对空字符串均无效。
空字符串即“ ”(只有双引号,或一个或多个空格),但在 Excel 表格、CSV、TXT 文档等是看不出来,pandas也把它当成有值进行操作。

我的思路是对整个dataframe替换空格为np.nan,于是看到replace方法里可以用正则替换,测试发现可以正确替换空字符串

df.replace(to_replace=r'^\s*$', value=np.nan, regex=True, inplace=True)

其中
r表示去掉反斜杠的转移机制
\s表示空白字符,匹配任何空白字符,包括空格、制表符、换页符等
^表示开始
*表示任意个
$表示结束

测试如下:

import pandas as pd
import numpy as np

data = {'a': [4, 6, 5, 7, 8],
        'b': ['w', '', ' ', 'x', 'z'],
        'c': [1, 0, 6, -5, 3],
        'd': [3, 4, 7, 10, 8],
        }
df = pd.DataFrame(data, index=['one', 'two', 'three', 'four', 'five'])
print(df)
print("==========替换==========")
df.replace(to_replace=r'^\s*$', value=np.nan, regex=True, inplace=True)
print(df)
print("==========有空值==========")
print(df[df.isnull().T.any()])

输出结果:

       a  b  c   d
one    4  w  1   3
two    6     0   4
three  5     6   7
four   7  x -5  10
five   8  z  3   8
==========替换==========
       a    b  c   d
one    4    w  1   3
two    6  NaN  0   4
three  5  NaN  6   7
four   7    x -5  10
five   8    z  3   8
==========有空值==========
       a    b  c  d
two    6  NaN  0  4
three  5  NaN  6  7
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值