我想找出我的数据的每一列中NaN的数量。
当前回答
可以使用df.iteritems()对数据帧进行循环。在for循环中设置一个条件来计算每列的NaN值百分比,并删除那些包含NaN值超过设置阈值的值:
for col, val in df.iteritems():
if (df[col].isnull().sum() / len(val) * 100) > 30:
df.drop(columns=col, inplace=True)
其他回答
下面是按列计数Null值的代码:
df.isna().sum()
你可以从非nan值的计数中减去总长度:
count_nan = len(df) - df.count()
你应该根据你的数据计算时间。与isnull解相比,小级数的速度提高了3倍。
import pandas as pd
import numpy as np
# example DataFrame
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
# count the NaNs in a column
num_nan_a = df.loc[ (pd.isna(df['a'])) , 'a' ].shape[0]
num_nan_b = df.loc[ (pd.isna(df['b'])) , 'b' ].shape[0]
# summarize the num_nan_b
print(df)
print(' ')
print(f"There are {num_nan_a} NaNs in column a")
print(f"There are {num_nan_b} NaNs in column b")
给出输出:
a b
0 1.0 NaN
1 2.0 1.0
2 NaN NaN
There are 1 NaNs in column a
There are 2 NaNs in column b
df.isnull().sum()
//type: <class 'pandas.core.series.Series'>
or
df.column_name.isnull().sum()
//type: <type 'numpy.int64'>
.sum df.isnull () () 将给出缺失值的列和。
如果你想知道特定列中缺失值的总和,那么以下代码将起作用:
推荐文章
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件
- 在Python中,使用argparse只允许正整数
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?