我想找出我的数据的每一列中NaN的数量。
当前回答
对于第一部分,我们有多种方法计算NaN。
方法1计数,由于计数将忽略与大小不同的NaN
print(len(df) - df.count())
方法2:isnull / isna chain with sum
print(df.isnull().sum())
#print(df.isna().sum())
方法3 describe / info:注意这将输出' notull '值计数
print(df.describe())
#print(df.info())
方法。
print(np.count_nonzero(np.isnan(df.values),axis=0))
对于问题的第二部分,如果我们想要在thresh中删除列,我们可以尝试dropna
thresh, optional要求多个非na值。
Thresh = n # no null value require, you can also get the by int(x% * len(df))
df = df.dropna(thresh = Thresh, axis = 1)
其他回答
你可以从非nan值的计数中减去总长度:
count_nan = len(df) - df.count()
你应该根据你的数据计算时间。与isnull解相比,小级数的速度提高了3倍。
对于第一部分,我们有多种方法计算NaN。
方法1计数,由于计数将忽略与大小不同的NaN
print(len(df) - df.count())
方法2:isnull / isna chain with sum
print(df.isnull().sum())
#print(df.isna().sum())
方法3 describe / info:注意这将输出' notull '值计数
print(df.describe())
#print(df.info())
方法。
print(np.count_nonzero(np.isnan(df.values),axis=0))
对于问题的第二部分,如果我们想要在thresh中删除列,我们可以尝试dropna
thresh, optional要求多个非na值。
Thresh = n # no null value require, you can also get the by int(x% * len(df))
df = df.dropna(thresh = Thresh, axis = 1)
使用isna()方法(或者它的别名isnull(),这也兼容较旧的pandas版本< 0.21.0),然后求和来计算NaN值。其中一列:
>>> s = pd.Series([1,2,3, np.nan, np.nan])
>>> s.isna().sum() # or s.isnull().sum() for older pandas versions
2
对于一些列,这也适用:
>>> df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
>>> df.isna().sum()
a 1
b 2
dtype: int64
另一种完整的方法是使用np。带有.isna()的count_non0:
np.count_nonzero(df.isna())
%timeit np.count_nonzero(df.isna())
512 ms ± 24.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
使用1000005行× 16列的数据框架与顶部答案进行比较:
%timeit df.isna().sum()
492 ms ± 55.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit df.isnull().sum(axis = 0)
478 ms ± 34.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit count_nan = len(df) - df.count()
484 ms ± 47.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
数据:
raw_data = {'first_name': ['Jason', np.nan, 'Tina', 'Jake', 'Amy'],
'last_name': ['Miller', np.nan, np.nan, 'Milner', 'Cooze'],
'age': [22, np.nan, 23, 24, 25],
'sex': ['m', np.nan, 'f', 'm', 'f'],
'Test1_Score': [4, np.nan, 0, 0, 0],
'Test2_Score': [25, np.nan, np.nan, 0, 0]}
results = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'sex', 'Test1_Score', 'Test2_Score'])
# big dataframe for %timeit
big_df = pd.DataFrame(np.random.randint(0, 100, size=(1000000, 10)), columns=list('ABCDEFGHIJ'))
df = pd.concat([big_df,results]) # 1000005 rows × 16 columns
数零:
df[df == 0].count(axis=0)
计算NaN:
df.isnull().sum()
or
df.isna().sum()
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 确定每列中NA值的个数
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 如何结合多个条件子集数据帧使用“或”?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式