计算 pandas DataFrame 中 NaN 的行数?

Count number of rows with NaN in a pandas DataFrame?

具有以下 运行 代码:

import datetime as dt
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

my_funds = [1, 2, 5, 7, 9, 11]
my_time = ['2020-01', '2019-12', '2019-11', '2019-10', '2019-09', '2019-08']
df = pd.DataFrame({'TIME': my_time, 'FUNDS':my_funds})

for x in range(2,3):
    df.insert(len(df.columns), f'x**{x}', df["FUNDS"]**x)

df = df.replace([1, 7, 9, 25],float('nan'))

print(df.isnull().values.ravel().sum())   #5 (obviously counting NaNs in total)
print(sum(map(any, df.isnull())))         #3 (I guess counting the NaNs in the left column)

我正在获取下面的数据框。我想获得 总行数 ,具有 1 个或多个 NaN,在我的例子中是 4,在行 - [0, 2, 3, 4].

使用:

print (df.isna().any(axis=1).sum())
4

解释:首先通过DataFrame.isna比较缺失值:

print (df.isna())
    TIME  FUNDS   x**2
0  False   True   True
1  False  False  False
2  False  False   True
3  False   True  False
4  False   True  False
5  False  False  False

并通过 DataFrame.any:

测试是否至少每行 True
print (df.isna().any(axis=1))
0     True
1    False
2     True
3     True
4     True
5    False
dtype: bool

最后计数 Truesum

另一个选项:

nan_rows = len(df[df["FUNDS"].isna() | df["x**2"].isna()])

新选项Series.clip

每行超过一个NaN取一个

df.isna().sum(axis=1).clip(upper=1).sum()
#4