选择列列表中至少有一个值不为空的行

时间:2016-08-20 04:36:11

标签: python pandas

我有一个包含许多列的大数据框(如1000)。我有一个列列表(由脚本生成~10)。我想选择原始数据框中的所有行,其中至少有一列我的列不为空。

因此,如果我事先知道我的列数,我可以这样做:

list_of_cols = ['col1', ...]
df[
  df[list_of_cols[0]].notnull() |
  df[list_of_cols[1]].notnull() |
  ...
  df[list_of_cols[6]].notnull() |
]

我也可以遍历cols列表并创建一个掩码然后我将应用于df,但他看起来太乏味了。知道熊猫在处理nan方面有多强大,我希望有一种更简单的方法来实现我想要的东西。

3 个答案:

答案 0 :(得分:2)

使用thresh方法中的dropna()参数。通过设置thresh=1,您可以指定如果至少有1个非空项,请不要删除它。

df = pd.DataFrame(np.random.choice((1., np.nan), (1000, 1000), p=(.3, .7)))
list_of_cols = list(range(10))

df[list_of_cols].dropna(thresh=1).head()

enter image description here

答案 1 :(得分:1)

从这开始:

data = {'a' :      [np.nan,0,0,0,0,0,np.nan,0,0,  0,0,0,    9,9,],
    'b' :      [np.nan,np.nan,1,1,1,1,1,1,1,  2,2,2,    1,7],
    'c' :      [np.nan,np.nan,1,1,2,2,3,3,3,  1,1,1,    1,1],
    'd' :      [np.nan,np.nan,7,9,6,9,7,np.nan,6,  6,7,6,    9,6]}

df = pd.DataFrame(data, columns=['a','b','c','d'])
df
      a    b    c    d
0   NaN  NaN  NaN  NaN
1   0.0  NaN  NaN  NaN
2   0.0  1.0  1.0  7.0
3   0.0  1.0  1.0  9.0
4   0.0  1.0  2.0  6.0
5   0.0  1.0  2.0  9.0
6   NaN  1.0  3.0  7.0
7   0.0  1.0  3.0  NaN
8   0.0  1.0  3.0  6.0
9   0.0  2.0  1.0  6.0
10  0.0  2.0  1.0  7.0
11  0.0  2.0  1.0  6.0
12  9.0  1.0  1.0  9.0
13  9.0  7.0  1.0  6.0

并非所有值都为空的行。 (删除行索引0)

df[~df.isnull().all(axis=1)]

      a    b    c    d
1   0.0  NaN  NaN  NaN
2   0.0  1.0  1.0  7.0
3   0.0  1.0  1.0  9.0
4   0.0  1.0  2.0  6.0
5   0.0  1.0  2.0  9.0
6   NaN  1.0  3.0  7.0
7   0.0  1.0  3.0  NaN
8   0.0  1.0  3.0  6.0
9   0.0  2.0  1.0  6.0
10  0.0  2.0  1.0  7.0
11  0.0  2.0  1.0  6.0
12  9.0  1.0  1.0  9.0
13  9.0  7.0  1.0  6.0

答案 2 :(得分:0)

可以使用boolean indexing

befores

<强>解释

表达式df[~pd.isnull(df[list_of_cols]).all(axis=1)] 返回一个布尔数组,作为过滤器应用于数据帧:

    应用于df[list_of_cols]).all(axis=1)
  • isnull()为数据框df[list_of_cols]创建了一个布尔掩码,df[list_of_cols] True中的空元素值为df[list_of_cols] 1}}否则

  • 如果所有元素均为False(行式True

    ,则
  • all()会返回True

因此,通过否定axis=1(并非所有null =至少一个非null),可以获得给定列列中至少有一个非null元素的所有行的掩码。

示例:

数据帧:

~

>>> df=pd.DataFrame({'A':[11,22,33,np.NaN], 'B':['x',np.NaN,np.NaN,'w'], 'C':['2016-03-13',np.NaN,'2016-03-14','2016-03-15']}) >>> df A B C 0 11 x 2016-03-13 1 22 NaN NaN 2 33 NaN 2016-03-14 3 NaN w 2016-03-15 面具:

isnull

逐行申请>>> ~pd.isnull(df[list_of_cols]) B C 0 True True 1 False False 2 False True 3 True True

all(axis=1)

从数据框中选择布尔值:

>>> ~pd.isnull(df[list_of_cols]).all(axis=1)
0     True
1    False
2     True
3     True
dtype: bool
相关问题