简体   繁体   English

Python,Pandas:只返回那些有缺失值的行

[英]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。”)

您可以使用any axis=1来检查每行是否至少有一个True ,然后使用布尔索引进行过滤:

null_data = df[df.isnull().any(axis=1)]
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.

相关问题 python 游标只返回那些第一列不为空的行 - python cursor return only those rows which first column is not empty 返回缺失值最少的行 pandas - Return rows that have the minimum amount of missing values pandas 如何为在另一列 pandas 中具有相同值的那些行使一列的值相同 - How to make same value of one column for those rows which have same values in another column pandas 如何仅保存 DataFrame 中的那些行,哪些列具有列表中的值? - How can I save only those rows from a DataFrame which columns have values from the list? 如何仅使用 Python pandas 将符合条件的行写入 excel 工作表 - How to write to excel sheet only those rows which match the condition using Python pandas 从 Pandas Dataframe 中选择一列中具有相同值而另一列仅缺失的行 - Selecting rows from Pandas Dataframe with same values in one column that have only missing in another 如何使用熊猫为序列中缺少的那些数据点有效地添加行? - How to efficiently add rows for those data points which are missing from a sequence using pandas? 从python中的pandas.DataFrame排除具有零值的行 - Excluding rows which have zero values from pandas.DataFrame in python Pandas 合并具有相似值的行中的值 - Pandas merging values in rows which have similar values 熊猫-根据列值添加缺少的行以具有linspace - pandas - add missing rows on the basis of column values to have linspace
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM