首页 > 解决方案 > 在 Pandas 中循环查找不是 NaN 的值

问题描述

我正在尝试创建一个语句,如果我的数据框中的对象不是 na 并且 Book_Status 为 True,则继续执行下一个任务。但是,当我尝试这样做时,我得到“float”对象没有属性“notna”。

我查看了 np.where,但这似乎是用来创建列的? 使用 np.where 循环

示例数据框

name       quote id       Book_Status
Park       foobar300      False
Bus        NaN            False
Car        NaN            False

这就是我的代码,它给了我我的错误

def BookEvent(df):
    y = 0
    for i in range(len(df_parking.index)):
        if df['quote id'][y].notna() & df['Book_Status'][y] == False:
          # Then do something unrelated to this df

标签: pythonpandasnull

解决方案


在您使用标量的解决方案中,因此需要pd.notna改为&使用and,但此循环解决方案很慢:

if pd.notna(df['quote id'][y]) and df['Book_Status'][y] == False:

但是在 pandas 中使用以下面具更好/更快:

mask = df['quote id'].notna() & ~df['Book_Status']
df['new'] = np.where(mask, 10, 20)

print (df)
   name   quote id  Book_Status  new
0  Park  foobar300        False   10
1   Bus        NaN        False   20
2   Car        NaN        False   20

推荐阅读