python - 如何遍历数据帧的行并检查列行中的值是否为 NaN

标签 python pandas iteration row dataframe

我有一个初学者问题。我有一个正在迭代的数据框,我想检查 column2 行中的值是否为 NaN,如果不是 NaN 则对该值执行操作>。我的数据框看起来像这样:

df:

  Column1  Column2
0    a        hey
1    b        NaN
2    c        up

我现在正在尝试的是:

for item, frame in df['Column2'].iteritems():
    if frame.notnull() == True:
        print 'frame'

这背后的想法是,我对第 2 列中的行和 print 帧中的每一行进行迭代,以获取具有值(字符串)的每一行。然而,我得到的是:

AttributeError                            Traceback (most recent call last)
<ipython-input-80-8b871a452417> in <module>()
      1 for item, frame in df['Column2'].iteritems():
----> 2     if frame.notnull() == True:
      3         print 'frame'

AttributeError: 'float' object has no attribute 'notnull'

当我只运行我的代码的第一行时,我得到了

0
hey
1
nan
2
up

这表明第一行输出中的 float 是错误的原因。任何人都可以告诉我如何才能完成我想要的吗?

最佳答案

如您所知,frame

for item, frame in df['Column2'].iteritems():

是列中的每个 ,它的类型是列中元素的类型(很可能不是 SeriesDataFrame)。因此,frame.notnull() 将不起作用。

你应该试试——

for item, frame in df['Column2'].iteritems():
    if pd.notnull(frame):
        print frame

关于python - 如何遍历数据帧的行并检查列行中的值是否为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33124117/

相关文章:

python - ClassName(object) 中的 super(ClassName, self) 有什么作用? (在 django 文档中使用)

python - 导入sklearn时出错

python - python中的return和break有什么区别?

python - R Reticulate - 以编程方式将定义的变量从 Python 环境移动到 R

javascript - 在 Node.js 的回调中影响对象的属性

python - # pandas DataFrame ValueError : Shape of passed values is (1, 3),索引意味着 (3, 3)

python - Pandas groupby 对象过滤

python - 计算每个类别的贡献

python - 在 python pandas DataFrame 中,如何向上移动行索引以填充空行?

python - 从文件中读取以获取并打印 JSON 数据