迭代数据帧并选择空值

时间:2016-12-22 16:01:01

标签: python dataframe null

我正在尝试遍历列= [myCol]的空值的数据帧。我可以很好地遍历数据帧,但是当我指定我只想看到空值时,我得到一个错误。

最终目标是我想强制一个值进入Null字段,这就是为什么我要迭代来识别哪个是第一个。

for index,row in df.iterrows():
    if(row['myCol'].isnull()):
        print('true')

AttributeError: 'str' object has no attribute 'isnull'

我尝试指定column ='None',因为这是我在打印数据帧迭代时看到的值。仍然没有运气:

for index,row in df.iterrows():
    if(row['myCol']=='None'):
        print('true')

No returned rows

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:6)

您可以使用pd.isnull()检查值是否为空:

for index, row in df.iterrows():
    if(pd.isnull(row['myCol'])):
        print('true')

但似乎需要df.fillna(myValue),其中myValue是您要强制进入NULL字段的值。此外,要检查数据框中的NULL字段,您可以调用df.myCol.isnull(),而不是循环遍历行并单独检查。

如果列是字符串类型,您可能还需要检查它是否为空字符串:

for index, row in df.iterrows():
    if(row['myCol'] == ""):
        print('true')