在 Python "The truth value of a Series is ambiguous Use a.empty, a.bool(), a.item(), a.any() or a.all().." 中获取 运行 代码时出错

Error getting when run code in Python "The truth value of a Series is ambiguous Use a.empty, a.bool(), a.item(), a.any() or a.all().."

当我 运行 下面的代码 Python

cols_with_missing = (col for col in new_data.columns if new_data[col].isnull().any())
for col in cols_with_missing:
    new_data[col + '_was_missing'] = new_data[col].isnull()

然后低于错误 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 这里 new_data 是 DataFrame.

试试下面的方法:

cols_with_missing = (col for col in new_data.columns if new_data[col].isnull().sum() > 0)
for col in cols_with_missing:
    new_data[col + '_was_missing'] = new_data[col].isnull()

问题是 Series.any() returns 一个新的 Series,如 documentation 中所述。

要获取单个值(标量),您需要将 None 作为轴参数传递。

cols_with_missing = (col for col in new_data.columns if new_data[col].isnull().any(None))