遍历dataframe并选择空值

2024-09-25 12:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

最终目标是,我想将一个值强制到空字段中,这就是为什么我要迭代以确定哪个是第一个字段。

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

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

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

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

No returned rows

非常感谢您的帮助!


Tags: 数据innonetruedataframedfforindex
1条回答
网友
1楼 · 发布于 2024-09-25 12:29:44

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

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

但似乎您需要df.fillna(myValue),其中myValue是您要强制进入空字段的值。还要检查数据帧中的NULL字段,您可以调用df.myCol.isnull(),而不是遍历行并逐个检查。


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

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

相关问题 更多 >