迭代数据帧并选择空值

Ari*_*iel 7 python null dataframe

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

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

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

AttributeError: 'str' object has no attribute 'isnull'
Run Code Online (Sandbox Code Playgroud)

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

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

No returned rows
Run Code Online (Sandbox Code Playgroud)

任何帮助非常感谢!

Psi*_*dom 6

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

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

但好像你需要的df.fillna(myValue)地方myValue是要强制值成是NULL字段.并且还要检查NULL数据框中的字段,您可以调用df.myCol.isnull()而不是循环遍历行并单独检查.


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

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