Drop a row in a Pandas Dataframe if any column contains a certain value, in said row

后端 未结 2 1756
野的像风
野的像风 2021-01-05 15:54

If we want to drop a row in which any column has a missing value we can do this:

df.dropna(axis = 0, how = \'any\', inplace = True)

How do

相关标签:
2条回答
  • 2021-01-05 16:52

    since you know, how to dropnan, you can replace it to NaN

    df=df.replace('Yourvalue',np.nan).dropna(axis = 0, how = 'any')
    
    0 讨论(0)
  • 2021-01-05 16:55

    Demo:

    Sample DF:

    In [7]: import string
    
    In [8]: df = pd.DataFrame(np.random.randint(100, size=(10,10)), columns=list(string.ascii_letters[:10]))
    
    In [9]: df
    Out[9]:
        a   b   c   d   e   f   g   h   i   j
    0  95  79  14  64  97   3   0  49  84   2
    1  52  82  72  40  55  26  21  69   2  35
    2  30  63  27  63  14  23  70  62  83  80
    3  23  90  96  43  75  23  27  47  83  40
    4  82  87  63  37  36  58  88  18  50  29
    5  92  29  93   6  62  85  87  74  21  32
    6  23  64  19  22  50  86  51  93  46   1
    7  56   0   8  46   1  56  82  15  55  45
    8  67  35  83  65  63  58  48  85  75  90
    9  12   7  45  28  33  98  42  93  78  12
    

    let's drop all rows containing at least one 0:

    In [10]: df.eq(0)
    Out[10]:
           a      b      c      d      e      f      g      h      i      j
    0  False  False  False  False  False  False   True  False  False  False
    1  False  False  False  False  False  False  False  False  False  False
    2  False  False  False  False  False  False  False  False  False  False
    3  False  False  False  False  False  False  False  False  False  False
    4  False  False  False  False  False  False  False  False  False  False
    5  False  False  False  False  False  False  False  False  False  False
    6  False  False  False  False  False  False  False  False  False  False
    7  False   True  False  False  False  False  False  False  False  False
    8  False  False  False  False  False  False  False  False  False  False
    9  False  False  False  False  False  False  False  False  False  False
    
    In [11]: res = df[~df.eq(0).any(1)]
    
    In [12]: res
    Out[12]:
        a   b   c   d   e   f   g   h   i   j
    1  52  82  72  40  55  26  21  69   2  35
    2  30  63  27  63  14  23  70  62  83  80
    3  23  90  96  43  75  23  27  47  83  40
    4  82  87  63  37  36  58  88  18  50  29
    5  92  29  93   6  62  85  87  74  21  32
    6  23  64  19  22  50  86  51  93  46   1
    8  67  35  83  65  63  58  48  85  75  90
    9  12   7  45  28  33  98  42  93  78  12
    
    0 讨论(0)
提交回复
热议问题