繁体   English   中英

计算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)

我得到下面的数据框。 我想获得总行数,在行[0, 2, 3, 4]上有 1 个或多个 NaN,在我的情况下为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

最后按sum计算True s。

另外一个选项:

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

新选项Series.clip

当每行有多个NaN时取一个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM