Vit*_*ata 1 python rows nan dataframe pandas
有以下运行代码:
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)
Run Code Online (Sandbox Code Playgroud)
我得到下面的数据框。我想获得总 rows 的计数,其中有 1 个或多个 NaN,在我的例子中是4,在 rows - 上[0, 2, 3, 4]。
使用:
print (df.isna().any(axis=1).sum())
4
Run Code Online (Sandbox Code Playgroud)
解释:首先通过以下方式比较缺失值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
Run Code Online (Sandbox Code Playgroud)
并测试至少每行是否True为DataFrame.any:
print (df.isna().any(axis=1))
0 True
1 False
2 True
3 True
4 True
5 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
最后计数Trues sum。