计算大熊猫DataFrame中带有NaN的行数?

时间:2020-02-06 13:42:59

标签: python pandas dataframe rows nan

具有以下运行代码:

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)

我正在获取下面的数据框。我想在行-[0, 2, 3, 4]上获得总行数,其中有1个或多个NaN,在我的情况下为 4

enter image description here

3 个答案:

答案 0 :(得分:3)

使用:

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

最后计数True的{​​{1}}个。

答案 1 :(得分:3)

另一个选择:

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

答案 2 :(得分:1)

新选项Series.clip

每行多于一个NaN时取一个

df.isna().sum(axis=1).clip(upper=1).sum()
#4
相关问题