深度阅读

How to check if a column contains null values in a Pandas DataFrame?

作者
作者
2023年08月22日
更新时间
15.35 分钟
阅读时间
0
阅读量

To check if a column contains null values in a Pandas DataFrame, you can use the isnull() method along with the any() method. Here’s an example:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, None], 'B': [4, None, 6]}) # create a DataFrame with columns A and B
is_b_null = df['B'].isnull().any() # check if column 'B' contains any null values
print(is_b_null)

Output:

True

In the example above, is_b_null stores a boolean value indicating whether column ‘B’ of the DataFrame contains any null values. The isnull() method returns a boolean mask with True values where the DataFrame is null and False where it is not null. The any() method returns True if any of the values in the resulting boolean mask are True, indicating that at least one null value exists in the column.

You can also check if any column in the entire DataFrame contains null values by calling the isnull() method on the entire DataFrame:

is_any_null = df.isnull().values.any() # check if any column in the DataFrame contains any null values
print(is_any_null)

Output:

True

In this example, is_any_null stores a boolean value indicating whether any column in the DataFrame contains any null values. The isnull() method returns a boolean mask for the entire DataFrame, and the values.any() method checks if any of the values in the mask are True.

Overall, checking if one or more columns in a Pandas DataFrame contain null values is straightforward using the isnull() and any() methods.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。