[英]Python, Pandas : Return only those rows which have missing values
While working in Pandas in Python...在 Python 中使用 Pandas 时...
I'm working with a dataset that contains some missing values, and I'd like to return a dataframe which contains only those rows which have missing data.我正在处理一个包含一些缺失值的数据集,我想返回一个数据框,其中只包含那些缺少数据的行。 Is there a nice way to do this?有没有很好的方法来做到这一点?
(My current method to do this is an inefficient "look to see what index isn't in the dataframe without the missing values, then make a df out of those indices.") (我目前执行此操作的方法是一种低效的“在没有缺失值的情况下查看数据框中没有哪些索引,然后从这些索引中创建 df。”)
df.isnull().any(axis = 1).sum()
这为您提供了至少一个缺失数据的总行数
如果您只想查看包含 NaN 值的行,您可以执行以下操作:
data_frame[data_frame.iloc[:, insert column number here]=='NaN']
您可以通过这种方式使用代码
sum(df.isnull().any(axis=1))
Similar to metersk's answer, 与meterk的答案类似,
null_data = df[np.logical_or.reduce(df.isnull().values, axis=1)]
Test 测试
n = 2
df = pd.DataFrame({'a':np.tile([0,1,2,3,4,np.nan],n),
'b':np.tile([0,1,2,3,np.nan,5],n)})
x = df[np.logical_or.reduce(df.isnull().values,axis=1)]
y = df[df.isnull().any(axis=1)]
x.equals(y)
我刚遇到这个问题我假设您想查看由我使用的缺失值的行组成的数据框部分
````df.loc[df.isnull().any(axis=1)]```
If you are looking for a quicker way to find the total number of missing rows in the dataframe, you can use this:如果您正在寻找一种更快的方法来查找数据框中缺失行的总数,您可以使用以下方法:
sum(df.isnull().values.any(axis=1)) sum(df.isnull().values.any(axis=1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.