Python-如果两列均为NaN,则删除行 [英] Python - Drop row if two columns are NaN
问题描述
This is an extension to this question, where OP wanted to know how to drop rows where the values in a single column are NaN.
我想知道如何在 2 (或更多)列均为 NaN 的情况下删除行.使用第二个答案的创建的数据框:
I'm wondering how I can drop rows where the values in 2 (or more) columns are both NaN. Using the second answer's created Data Frame:
In [1]: df = pd.DataFrame(np.random.randn(10,3))
In [2]: df.ix[::2,0] = np.nan; df.ix[::4,1] = np.nan; df.ix[::3,2] = np.nan;
In [3]: df
Out[3]:
0 1 2
0 NaN NaN NaN
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
4 NaN NaN 0.050742
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
8 NaN NaN 0.637482
9 -0.310130 0.078891 NaN
如果我使用drop.na()
命令(特别是drop.na(subset=[1,2])
),则会完成一个或"类型的放置并离开:
If I use the drop.na()
command, specifically the drop.na(subset=[1,2])
, then it completes an "or" type drop and leaves:
In[4]: df.dropna(subset=[1,2])
Out[4]:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
5 -1.250970 0.030561 -2.678622
7 0.049896 -0.308003 0.823295
我想要的是一个和"类型的放置,它将放置在列索引1 和 2中有NaN
的行中.这会留下:
What I want is an "and" type drop, where it drops rows where there is an NaN
in column index 1 and 2. This would leave:
0 1 2
1 2.677677 -1.466923 -0.750366
2 NaN 0.798002 -0.906038
3 0.672201 0.964789 NaN
4 NaN NaN 0.050742
5 -1.250970 0.030561 -2.678622
6 NaN 1.036043 NaN
7 0.049896 -0.308003 0.823295
8 NaN NaN 0.637482
9 -0.310130 0.078891 NaN
仅放置第一行的地方.
有什么想法吗?
更改数据框的值以保持一致性
changed data frame values for consistency
推荐答案
以下两个之一:
df.dropna(subset=[1, 2], how='all')
或
df.dropna(subset=[1, 2], thresh=1)
这篇关于Python-如果两列均为NaN,则删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!